3

I use React to build a web app that stores documents. Those are created in HTML and are then stored in a database. To show them in the app I load the HTML inside a div by making use of dangerouslySetInnerHTML.

<div dangerouslySetInnerHTML={{__html: this.props.page.content}} />

Even through this works perfectly fine, the name dangerouslySetInnerHTML suggests to pay more attention to this case, but I wonder what exactly can be done to remain flexible enough to load HTML and make it appear in the web app. I believe that the word dangerous addresses the danger of cross-site scripting, meaning that a script could be injected, executing harmful code.

As a countermeasure I thought of cleaning the HTML code before parsing it over to the div. One library addressing this is DOMPurify. Another way would be to convert the HTML code from the database directly into React Elements using html-react-parser.

Would that be the right approach? Or are there alternatives to dangerouslySetInnerHTML?

Socrates
  • 8,724
  • 25
  • 66
  • 113
  • 2
    `dangerouslySetInnerHTML` is called so to make sure that you know what you are doing. There is no safe way to achieve this without some cleaning of the HTML code unless you trust the code in the database. – UjinT34 Nov 23 '18 at 17:00
  • Looks like a duplicate of: https://stackoverflow.com/questions/29044518/safe-alternative-to-dangerouslysetinnerhtml – theUtherSide Feb 14 '19 at 13:03
  • Possible duplicate of [Safe alternative to dangerouslySetInnerHTML](https://stackoverflow.com/questions/29044518/safe-alternative-to-dangerouslysetinnerhtml) – Michael Freidgeim Sep 05 '19 at 08:06

1 Answers1

6

Perhaps these parsers can fulfill ur need

html-to-react

html-react-parser

Jimubao
  • 411
  • 6
  • 11