I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
and to insert it into react like so, and have it work?
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work.
By using '' the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element -
''
and it would work<Fragment>
to return a HTML element.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:
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.
Very Simple :)
You can use dangerouslySetInnerHTML, e.g.
You can also include this HTML in ReactDOM like this:
Here are two links link and link2 from React documentation which could be helpful.
By using
''
you are making it to string. Use without inverted commas it will work fine.