Parse HTML entities in React

If you are working in React and are fetching data from an API that is returning some content with mixed HTML entities. You will notice that when you are rendering the HTML data in React, the HTML entities does not gets rendered properly. It is because React does not parse HTML entities by default.

Today, we will show you a way that let’s you parse HTML entities in React. First, let’s say we have a following React component that displays a text having an HTML entity.

function MyApp() {
	const [myVar, setMyVar] = React.useState("©");

	return (
		<h1>Parse HTML entities in React: { myVar }</h1>
	)
}

Right now, it will output:

Parse HTML entities in React: &copy;

You can see that the &copy; HTML entity is not parsed properly. In order to parse it, we will use a library called html-react-parser. This library allows you to parse HTML to React. If you are developing your backend in Node.js, then this library can be used on both sides, frontend and backend.

You need to include the library in your project using it’s production link:

<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>

You can also download this JS file and paste in your project and use relative path. Finally, you need to call the “HTMLReactParser(var string)” function and send your variable as an argument.

{ HTMLReactParser(myVar) }

If you run the page now, you will see that your HTML entity has been parsed properly.