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 dangerouslySetInnerHTML
attribute
Through the third-party react-html-parser
library
In this Answer, we’ll discuss both methods.
dangerouslySetInnerHTML
attributeIn 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 the content
, which contains a basic HTML in a div
.
Line 18: We insert the content
of the current state in the div. The dangerouslySetInnerHTML
object has a single property __html
that 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.
react-html-parser
libraryThe 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 ReactHtmlParser
library.
Lines 7–12: We set the state of the component App
. The state contains the content
, which contains a basic HTML in a div
.
Line 19: We pass the content
of the current state to the ReactHtmlParser
function, which parses the HTML string and returns a tree of React elements. These elements are rendered in the div
.
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