I have a String and want to render it in react JS
const htmlString = "<h1>
<Ref description=\"Magic may or may not be happening\"> hello magic</Ref></h1>"
return ( <div> <h1>
{htmlString}</h1>
</div\>)
Can I render this htmlString in react js Please help!
CodePudding user response:
You can use react-html-parser
to achieve this
import React from 'react';
import ReactHtmlParser from 'react-html-parser';
class HtmlComponent extends React.Component {
render() {
const html = '<div>Example HTML string</div>';
return <div>{ ReactHtmlParser(html) }</div>;
}
}
See docs here
CodePudding user response:
You can use dangerouslySetInnerHTML attribute on an html element to set the string as HTML. But know that setting HTML like this in React is risky as this may expose your users to a cross-site scripting (XSS) attack. To know more on how to use it, refer here on official React docs: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
Posting an example use-case below on how to use it.
function App() {
function getMarkup() {
return {__html: '<h3>My Content here..</h3>'}; // The HTML string you want to set
}
return (
<div className="App">
<div dangerouslySetInnerHTML={getMarkup()}></div>
</div>
);
}