Sometimes you are served raw HTML from an API that you want to display in React and you need to modify or add attributes to certain elements inside.

For this example, we will add the target="_blank" attribute to all anchors inside of an HTML string, which will cause the links to be opened in a new browser tab.

Parsing HTML is extremly tricky, so we will leverage an existing package for this:

npm i react-html-parser

Once we have it installed, we'll create a new utility function to handle transforming the html, called HtmlTransformer:

import ReactHtmlParser from "react-html-parser"

export default function HtmlTransformer(html)
{
    return ReactHtmlParser(html, {
        transform(node) {
            if (node.type === 'tag' && node.name === 'a') {
                node.attribs.target = "_blank"
            }
        }
    });
}
We're simply adding the target attribute here if the node is an anchor tag.

Now we can import this into any React component if we need to transform links inside of any HTML to be opened externally:

import HtmlTransformer from "../utilities/html_transformer"

export default function Article({ html })
{
    return (
    	<div>{HtmlTransformer(html)}</div>
    )
}
Don't worry, HTML is sanitized before it is rendered.

And that's it!