Render a string as HTML in React

If you're working with React and you need to render a string as HTML, there are a few options available to you. You can use the built-in dangerouslySetInnerHTML prop, you can use a third-party library like DOMPurify, or you can write your own function to handle the conversion. Whichever option you choose, be sure to take care when handling user input, as it's possible for malicious actors to inject code into your app that can wreak havoc.

function app() {
    const html_str = '<h1 style="color:red;">something</h1>';

    return (
        <div dangerouslySetInnerHTML={{ __html: html_str }} />

The code example above is a function that returns a div element. The div element has a property called dangerouslySetInnerHTML. The value of this property is set to an object with a key of __html and a value of html_str. The html_str variable is a string that contains HTML. This allows the HTML to be rendered as part of the div element.

Was this helpful?