How to render HTML in a state string
In React, state refers to an internal data storage mechanism that allows a component to store and manage its data. It helps improve the reactivity of the React application because the component is rerendered, and changes are reflected on the user interface the moment a state is updated.
There are two ways to render an HTML in the state string:
Through the
dangerouslySetInnerHTMLattributeThrough the third-party
react-html-parserlibrary
In this Answer, we’ll discuss both methods.
Rendering HTML using the dangerouslySetInnerHTML attribute
In React, dangerouslySetInnerHTML is an attribute that allows us to inject raw HTML content into a component’s rendered output. We can use this attribute as shown in the code snippet below:
<div dangerouslySetInnerHTML={{ __html: this.state.content }} />
In this Answer, we’ll render the HTML content in the state of the component App. Run the code below to see the output.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
require('./style.css');
ReactDOM.render(
<App />,
document.getElementById('root')
);
In the code given above, the file app.js defines the component App. We implement the following steps in the code:
Lines 6–11: We set the state of the component
App. The state contains thecontent, which contains a basic HTML in adiv.Line 18: We insert the
contentof the current state in the div. ThedangerouslySetInnerHTMLobject has a single property__htmlthat holds the actual content of the element.
Note: The name “dangerously” emphasizes that using this attribute can pose security risks if not used carefully because it bypasses React’s built-in protections against Cross-Site Scripting (XSS) attacks. Therefore, it should be used sparingly and only with trusted content.
Rendering HTML using the react-html-parser library
The react-html-parser library converts an HTML string to a React element. Run the following command to install the library using npm:
npm install react-html-parser
We render the HTML content in the state of the App component. Run the code below to see the output.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
require('./style.css');
ReactDOM.render(
<App />,
document.getElementById('root')
);
In the code given above, the app.js file defines the App component. Here are the steps implemented in the code:
Line 2: We import the
ReactHtmlParserlibrary.Lines 7–12: We set the state of the component
App. The state contains thecontent, which contains a basic HTML in adiv.Line 19: We pass the
contentof the current state to theReactHtmlParserfunction, which parses the HTML string and returns a tree of React elements. These elements are rendered in thediv.
Both methods discussed above are commonly used to render an HTML in the state string. However, the react-html-parser package helps us avoid dangerously setting up the inner HTML and ensures security.
Free Resources