Open In App

How to use innerHtml in React JS ?

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React.js provides a easy way of handling UI updates. However, sometimes you need to inject HTML directly into your components.

Prerequisites

In this article, we are going to learn how can we use InnerHTML in React JS. We can add HTML into ReactJS by using the ‘dangerouslySetInnerHTML’ property. As the name suggests it is dangerous because it directly injects HTML into your react components, which can lead to security issues and other manipulative problems. It can also increase risks like cross-site scripting (XSS).

Steps to Create the React Application

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Project Structure:

pppppppp

Project structure

Example: Here we are creating a component ‘HTML’ in which we are creating a const and storing a html element as a value and passing that value in a div element for dangerouslySetInnerHTML , So that we can inject that HTML in out Reactjs component and render it on screen. After that we are importing that ‘HTML’ component in App.js file and it will render to the screen.

Javascript




//HTML.js
import React from 'react';
 
function HTML() {
    const htmlContent =
        `<div>
            <h3>
                GeekForGeeks
            </h3>
            <p>
                innerHTML in reactjs
            </p>
         </div>`;
 
    return (
        <div>
            <div dangerouslySetInnerHTML={
                { __html: htmlContent }
             } />
        </div>
    );
}
 
export default HTML;


Javascript




//App.js
 
import './App.css';
import HTML from './HTML';
function App() {
    return (
 
        <div className="center">
            <HTML />
        </div>
 
    );
}
 
export default App;


Steps to run the application:

npm start

Output:

plplp

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads