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
Now we can import this into any React component if we need to transform links inside of any HTML to be opened externally:
And that's it!