Skip to content

Instantly share code, notes, and snippets.

@SkReD
Last active July 14, 2021 01:05
Show Gist options
  • Save SkReD/76b188f90759ead50bd7250744040073 to your computer and use it in GitHub Desktop.
Save SkReD/76b188f90759ead50bd7250744040073 to your computer and use it in GitHub Desktop.
import React from 'react';
function styleStringToObject(styleStr) {
return styleStr.split(';').reduce((acc, pair) => {
const [name, ...valueParts] = pair.trim().split(':');
return {
...acc,
[name.trim()]: valueParts.join(':').trim(),
};
}, {});
}
const startTagRegex = /^<(.+?)>/;
export function htmlToReactElementWithInnerHtml(html) {
const rootTagContentMatch = startTagRegex.exec(html);
if (!rootTagContentMatch) {
return null;
}
const [fullMatch, content] = rootTagContentMatch;
const htmlAttrsRegex = /\s(\w+)="(.+?)"/g;
let match;
const argPairs = [];
while ((match = htmlAttrsRegex.exec(content))) {
argPairs.push([match[1], match[2]]);
}
const [rootTag] = content.split(' ');
const rootProps = argPairs.reduce(
(acc, [name, value]) => ({
...acc,
[name]: name === 'style' ? styleStringToObject(value) : value,
}),
{}
);
return React.createElement(rootTag, {
dangerouslySetInnerHTML: {
__html: html.slice(fullMatch.length, html.lastIndexOf(`</${rootTag}>`)),
},
...rootProps,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment