» npm install html-react-parser
» npm install react-html-parser
Videos
» npm install @types/react-html-parser
» npm install react-native-html-parser
» npm install @burst/react-html-parser
You probably want to look deeper into dangerouslySetInnerHTML. Here is an example how to render HTML from a string in a React component:
import React from 'react';
import { render } from 'react-dom';
const htmlString = '<h1>Hello World! </h1>';
const App = () => (
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
);
render(<App />, document.getElementById('root'));
Full example here: https://codesandbox.io/s/xv40xXQzE
Read more about dangerouslySetInnerHTML in the React docs here: https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml
As pointed out in this answer by EsterlingAccimeYoutuber, you can use a parser in case you don't want to use dangerouslySetInnerHTML attribute.
By now, react-html-parser has not been updated for 3 years, so I went looking for a different module.
html-react-parser does same job but is frequently maintained and updated.
It should be good practice to sanitize your html-String to prevent XSS attacks. dompurify can be used for that.
I updated EsterlingAccimeYoutuber's code-example to the following:
import React from 'react';
import { render } from 'react-dom';
import parse from 'html-react-parser';
import DOMPurify from 'dompurify';
const SpecialButton = ({ children, color }) => (
<button style={{color}}>{children}</button>
);
const htmlFromCMS = `
<div>Hi,
<SpecialButton color="red">My Button</SpecialButton>
</div>`;
const htmlFrom = (htmlString) => {
const cleanHtmlString = DOMPurify.sanitize(htmlString,
{ USE_PROFILES: { html: true } });
const html = parse(cleanHtmlString);
return html;
}
const App = () => (
<div>
{htmlFromCMS && htmlFrom(htmlFromCMS)}
</div>
);
render(<App />, document.getElementById('root'));
Inspired by original post above, hence special thanks to original authors!
Here is a solution I found in the following answer
The idea is to replace react-html-parser with html-react-parser.
import parse from "html-react-parser";
...
{parse("<HTML string>")}
...
Instead of using react-html-parser, why don't you use html-react-parser ?
react-html-parser updated 5 years ago, I think something in the body doesn't "match" with current version of react. hmtl-react-parser is updated 7 days ago.