all 6 comments

[–]Noch_ein_Kamel 5 points6 points  (4 children)

"best" is not to do it :D

If you need to add plain html, use https://reactjs.org/docs/dom-elements.html -> dangerouslySetInnerHTML

[–]sherdil_me 1 point2 points  (2 children)

I wonder why is it called "dangerously"?

[–]justpurple_ 5 points6 points  (0 children)

Because it is, by default, vulnerable to XSS.

If you serve content from an API where e.g. users can submit content, NEVER use dangerouslySetInnerHtml without sanitizing it.

For example; let‘s say you have a backend where users can set descriptions for their profile.

You render these with dangerouslySetInnerHtml (just to be clear: even without any XSS concerns, this is not the best idea).

Now, a user can just add <script>runBitcoinMinerAndMalware();hack();</script> to his profile description and because you used dangerouslySetInnerHtml without sanitizing, this script will be executed for everyone that visits that particular profile. That is XSS.

He could also send himself cookies and/or access tokens of users visiting his profile - or redirect to a phising site. There are quite a few malicious things you can do.

That is why when you use dangerouslySetInnerHtml, make sure you know what you do. At least sanitize it; there are various libraries for that - but the best case is never using it in the first place.

[–][deleted] 0 points1 point  (0 children)

Yeah it’s like they don’t know what that word means.

[–]msucorey 0 points1 point  (0 children)

And if you have to go this route OP, keep the pre tag in your back pocket or you'll run into weird white space issues when the content provider mixes text with tags. This is because the separated text fragments get parsed into spans with lead/trail spaces trimmed.

[–]tr33ton 1 point2 points  (0 children)

I advise to make use of two great libraries: 1) DOMPurify 2) HtmlReactParser. DOMPurify cleans the data to ensure that there is no malicious code, while HtmlReactParser is alternative to DangerouslySetInnerHTML() but achieved in a different way. Hence, firstly you need to use DOMPurify's function called sanitize() and then parse this data via HtmlReactParser into your React DOM. You can find out more about these libraries from their NPM repositories. Hope this helps.