Horje
How to use innerHtml in React JS ?

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




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How To Create a Delay Function in ReactJS ? How To Create a Delay Function in ReactJS ?
How to Set z-index Value in React JS ? How to Set z-index Value in React JS ?
How to Create a Simple Counter App using Next.js ? How to Create a Simple Counter App using Next.js ?
How to Convert Input Value in Md5 using React JS ? How to Convert Input Value in Md5 using React JS ?
How to Disable a Button in React JS ? How to Disable a Button in React JS ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14