Insert HTML with React Variable Statements (JSX) [duplicate] Insert HTML with React Variable Statements (JSX) [duplicate] reactjs reactjs

Insert HTML with React Variable Statements (JSX) [duplicate]


You can use dangerouslySetInnerHTML, e.g.

render: function() {    return (        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>    );}


Note that dangerouslySetInnerHTML can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.

It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.

Example:

import DOMPurify from 'dompurify'const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';render: function() {    return (        <div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>    );}


dangerouslySetInnerHTML has many disadvantage because it set inside the tag.

I suggest you to use some react wrapper like i found one here on npm for this purpose.html-react-parser does the same job.

import Parser from 'html-react-parser';var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';render: function() {    return (        <div className="content">{Parser(thisIsMyCopy)}</div>    );}

Very Simple :)