» npm install html-react-parser
» npm install @types/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!
When you do {Reason.value} it assumes Reason.value is text so it escapes all the HTML characters you are using.
To accomplish what you want you'll need to manually set the HTML.
In react you do this with dangerouslySetInnerHtml - this can leave you vulnerable to XSS attacks.
<div dangerouslySetInnerHTML={{ __html: Reason.value }}></div>
I just found the solution in my project - React- typescript where I'm fetching html block from different service. Here is the simplified version
type Props = {
htmlString: string;
};
export function HtmlStringComponent({ htmlString }: Props) {
return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
}