Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
62 lines (46 sloc) 1.67 KB
layout title date excerpt categories
post
Dangerously set innerHTML alternative
2016-10-07 13:36:00 -4000
An alternative to React's dangerouslySetInnerHTML is html-react-parser, which converts an HTML string to React elements.
react javascript babel html npm

There may be an occasion that you need to render an HTML string when using React.

In most situations, dangerouslySetInnerHTML should suffice:

{% raw %}

<div dangerouslySetInnerHTML={{
    __html: '<em>foo</em>'
}} />

{% endraw %}

But are there any other alternatives?

There are, and one of them is called html-react-parser.

Usage

First install the package and its dependencies:

$ npm install html-react-parser react react-dom

Now you can do something like this:

<div>
    {require('html-react-parser')(
        '<em>foo</em>'
    )}
</div>

When parsing the HTML string, you can even replace HTML elements with your own custom React elements:

import Parser from 'html-react-parser';

<div>
    {Parser('<em>foo</em>', {
        replace: (domNode) => {
            if (domNode.name === 'em') {
                return <strong>bar</strong>;
            }
        }
    })}
</div>

Want to play with it some more? Check out the repository and this fiddle:

<script async src="//jsfiddle.net/remarkablemark/7v86d800/embed/js,html,result/dark/"></script>