How to use innerHtml in React JS ?
Last Updated :
29 Nov, 2023
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:
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
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
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:
Output
Share your thoughts in the comments
Please Login to comment...