I want to render a large chunk of html by replacing specific tags such as <p> and <a> with React components(i.e. <StyledParagraph> and <StyledLink>)
I've tested many libraries including html-react-parser. Unlike many others, html-react-parser has an example that addresses my need. But, I cannot get the example to work. (Using React 16.5.3)
const test = () =>
<>
{parse(
`
<p id="main">
<span class="prettify">
keep me and make me pretty!
</span>
</p>
`,
{
replace: ({ attribs, children }) => {
if (!attribs) return;
if (attribs.id === 'main') {
return (
<h1 style={{ fontSize: 42 }}>
{domToReact(children)}
</h1>
);
} else if (attribs.class === 'prettify') {
return (
<span style={{ color: 'hotpink' }}>
{domToReact(children)}
</span>
);
}
}
}
)}
</>
I did not pass parserOptions to the domToReact function, because I haven't found the documentation for those options yet.
Expected results:
<h1 style="font-size:42px">
<span style="color:hotpink">keep me and make me pretty!</span>
</h1>
So far, I cannot modify the nested nodes (in this case <span>).
Actual results:
<h1 style="font-size: 42px;">
<span class="prettify">keep me and make me pretty!</span>
</h1>
You have to pass a
replacefunction todomToReactas part of itsoptionsparam. From the source:In the case of this example that would mean...