Yes there is a difference!
The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected HTML.
However, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.
Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.
More importantly, if you simply use innerHTML, React has no way to know the DOM node has been modified. The next time the render function is called, React will overwrite the content that was manually injected with what it thinks the correct state of that DOM node should be.
Your solution to use componentDidUpdate to always ensure the content is in sync I believe would work but there might be a flash during each render.
Yes there is a difference!
The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected HTML.
However, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.
Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.
More importantly, if you simply use innerHTML, React has no way to know the DOM node has been modified. The next time the render function is called, React will overwrite the content that was manually injected with what it thinks the correct state of that DOM node should be.
Your solution to use componentDidUpdate to always ensure the content is in sync I believe would work but there might be a flash during each render.
You can bind to dom directly
<div dangerouslySetInnerHTML={{__html: '<p>First · Second</p>'}}></div>
Alternatives to dangerouslySetInnerHTML
Newest 'dangerouslysetinnerhtml' Questions - Stack Overflow
Don't dangerously set innerHTML on anything other than a div!
Is it a security to risk to use innerHTML to inject html even if you set the value yourself?
Videos
» npm install dangerously-set-html-content
I have to render some small snippets of HTML in a control. The source is trusted and the app is internal but i still cannot take any XSS chances.
I have to render html from an email body bc apparently HTML is hard for digital marketing people to read haha..
I was thinking about some sanitization library but found this: https://github.com/remarkablemark/html-react-parser which i havent reviewed to deeply yet.
Anybody been down this road and can help a brother out with a recommendation?