Adding attributes to HTML in React

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 extremely tricky, so we will leverage an existing package for this:

1npm i react-html-parser

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

1import ReactHtmlParser from "react-html-parser"
3export default function HtmlTransformer(html)
5 return ReactHtmlParser(html, {
6 transform(node) {
7 if (node.type === 'tag' && === 'a') {
8 = "_blank"
9 }
10 }
11 });

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

1import HtmlTransformer from "../utilities/html_transformer"
3export default function Article({ html })
5 return (
6 <div>{HtmlTransformer(html)}</div>
7 )

And that's it!