Open In App

ReactJS dangerouslySetInnerHTML Attribute

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The dangerouslySetInnerHTML attribute in react is used to inject raw HTML directly into a component. It enables direct DOM Manipulation in React. It is dangerous as it can potentially expose the application to cross-site scripting attacks.

Syntax:

<div dangerouslySetInnerHTML={{ __html: '<p>Your HTML here</p>' }} />

In class-based components, the dangerouslySetInnerHTML attribute is used to set innerHTML for the page. This is the replacement for innerHTML attribute.

Steps to Create 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:

It will look like the following.

Example: This example demonstrates the use of dangerouslySetInnerHTML to dynamically inject raw html in the component.

// Filename - App.js

import React from "react";

// Defining our App Component
const App = () => {
    // Function to demonstrate dangerouslySetInnerHTML attribute
    function Set() {
        return {
            __html: "Setting HTML using dangerouslySetInnerHTML attribute"
        };
    }

    // Returning our JSX code
    return (
        <>
            <div>
                <h1>GeeksforGeeks</h1>
                <div dangerouslySetInnerHTML={Set()}></div>
            </div>
        </>
    );
};

// Exporting your Default App Component
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:



Next Article

Similar Reads

three90RightbarBannerImg