Search code examples
htmlreactjsjsxcode-injectiontsx

Alternative to dangerouslySetInnerHTML


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?


Solution

  • Perhaps these parsers can fulfill ur need

    html-to-react

    html-react-parser