Last active
July 14, 2021 01:05
-
-
Save SkReD/76b188f90759ead50bd7250744040073 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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