For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentUsing dangerouslySetInnerHTML - Getting Started with DOM 

Using dangerouslySetInnerHTML - Getting Started with DOM 

Published
05th Sep, 2023
Views
view count loader
Read it in
9 Mins
In this article
    Using dangerouslySetInnerHTML - Getting Started with DOM 

    The React framework has just about everything you will need to produce a high-quality web application that scales to any size. However, sometimes we might want to manipulate the DOM elements in a hacky way. Read more about markup language by checking the detailed article on what is mardown.

    This is where the React dangerouslySetInnerHTML property comes in. In this tutorial, you will learn with examples of when and how to use dangerouslySetInnerHTML in a React Js JSX component. Check out our react full course now if you want to accelerate your dev skills on the go. 

    But before that, let’s get started with dangerouslySetInnerHTML in React.

    What is dangerouslySetInnerHTML in React, and Why Is It Called So? 

    You may ask, what is dangerouslySetInnerHTML, and why does it sound dangerous? Don’t be freaked out; let’s use this illustration to explain.

    React uses a browser-independent system to manipulate the DOM elements. This means it does not interact directly with the DOM. As a result, you will notice that you are not permitted to add HTML strings directly in React.

    For example, observe how the code below produced a markup not interpreted by the browser…

    const post = "<p>Blog Post With Markups</p>";
    export default function App() {
      return <div>{post}</div>;
    }
    <p>Blog Post With Markups</p>

    The output above depicts the issue of inserting HTML code inside a JSX element without using the dangerouslySetInnerHTML react component property. Because React JSX sanitizes the output to prevent cross-site scripting, the HTML code will not be properly represented (XSS).

    You may be wondering why to React does not allow this operation by default.

    The React team has decided to add a second layer of security to your application to protect it from XSS attacks. Simply injecting HTML code into a JSX component is not secure, primarily because it exposes your app to Cross-Site Scripting (XSS) attacks.

    As a result, the name of this react prop is particularly terrifying as dangerouslySetInnerHTML.

    Syntax and Need to Use dangerouslySetInnerHTML

    Here is a simple illustration of dangerouslySetInnerHTML…

    <div dangerouslySetInnerHTML={{ __html: value }}/>

    Observe that the dangerouslySetInnerHTML is assigned an object with a __html key, and the value is the HTML code you wish to inject into your application.

    Using the dangerouslySetInnerHTML react js property is particularly useful for displaying markup contents retrieved from an external API.

    When to Use dangerouslySetInnerHTML

    A use-case to properly dipict the benefit of using dangerouslySetInnerHTML in your project can be seen in the image below. 

    When to Use dangerouslySetInnerHTML

    dangerouslySetInnerHTML reactjs property can be a lifesaver when used for rendering HTML markups produced by a WYSIWYG editor.

    For example, online media and news agencies use WYSIWYG editors to write stories that interest their readers. Their formatted text contents are saved in the database as sanitized HTML codes and later rendered on the view.

    In React, you will need the dangerouslySetInnerHTML property to display the formatted HTML code on the view.

    How to Use dangerouslySetInnerHTML in React

    Let’s go into detail on how to effectively use dangerouslySetInnerHTML in a ReactJs project.

    Render HTML without dangerouslySetInnerHTML in React

    Consider the following example, it shows us a situation when you try to render some markup to the view without using the dangerouslySetInnerHTML property.

    const markdown = `
      <h1>How Blockchain is Saving the World</h1>
      <p>
        In his last public speech,
        the <strong>founder</strong> of the popular 
        blockchain network, <em>Vitalic Buterin</em>
        said...
      </p>
    `;
    export default function App() {
      return <div>{markdown}</div>;
    }

    And here is the result…

    <h1>How Blockchain is Saving the World</h1> <p> In his last public speech, the <strong>founder</strong> of the popular blockchain network, <em>Vitalic Buterin</em> said... </p>

    The above code shows us a situation where you try to render HTML markup without using the dangerouslySetInnerHTML React property

    Just adding the dangerouslySetInnerHTML property to your JSX element, interpretation is immediately given to your markup as seen in the example below:

    const markdown = `
      <h1>How Blockchain is Saving the World</h1>
      <p>
        In his last public speech, <br>
        the <strong>founder</strong> of the popular 
        blockchain network, <br> <em>Vitalic Buterin</em>
        said...
      </p>
    `;
    export default function App() {
      return (
        <div dangerouslySetInnerHTML={{ __html: markdown }} />
      );
    }

    And here is how the result looks like…

    How Blockchain is Saving the World

    In his last public speech,  

    the founder of the popular blockchain network,  

    Vitalic Buterin said...

    Remember, using dangerouslySetInnerHTML reactjs property without sanitizing will make your application vulnerable to XSS attacks. Shortly, you will learn how to curb XSS attacks using the DOMPurify package.

    Why There are No dangerouslySetInnerHTML React Alternatives

    There isn’t a prebuilt alternative to the dangerouslySetInnerHTML property in React yet. A good reason is because of the vulnerability (XSS attack) associated with the property. And because the current property works just fine, there hasn’t been any compelling need for an alternative.

    If you're the only one entering data on your website, you can rest assured that it won't be contaminated.

    However, if the application or site accepts multiple users' data input, you should be concerned.

    However, apart from that, there is one alternative to using dangerouslySetInnerHTML, simply setting innerHTML of a React HTML element using vanilla JS instead. Consider this alternative Vanilla JavaScript example below…

    document.getElementsByTagName(‘p’)[0].innerHTML = `
      In his last public speech, <br>
      the <strong>founder</strong> 
      of the popular blockchain network, <br>
      <em>Vitalic Buterin</em> said...

    You can enroll yourself for web development course online to get deeply acquainted with react.

    How Do We Use It Safely?

    To use the React dangerouslySetInnerHTML property safely on your project, you combine it with a sanitization package to ensure that you are not rendering an executable script on the page.

    This is an example of rendering malicious executable script on page…

    How Do We Use It Safely?

    You don’t want to render a malicious script on the page; this is why you need a sanitization package that will render a malicious script useless. We use a popular package called DOM purify for sanitizing it.

    Install DOMPurify

    DOMPurify, an npm package created by more than 60 web security experts to sanitize HTML code and prevent XSS attacks, is the most popular package for sanitizing a markup in React.

    DOMPurify is a DOM-only, lightning-fast, and incredibly forgiving XSS sanitizer for HTML, MathML, and SVG. The package had over 2.3 million weekly downloads at the time of writing this tutorial.

    DOMPurify can help us improve the security of our injected HTML code from dangerouslySetInnerHTML. This is how you will incorporate the DOMPurify package into your project.

    The first step is to install the package and then run the following code on your terminal...

    npm install dompurify

    Import package

    Next, let’s install the package into the component you wish to use it on, see the code below…

    import DOMPurify from "dompurify";

    Sanitize

    Lastly, let’s apply the sanitization function to curb XSS vulnerabilities…

    <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(markup) }}/>

    Markup represents the HTML codes you wish to sanitize, and the sanitize is a method within the DOMPurify that does the sanitization task.

    Now let’s revamp the example code we previously wrote to include the React dangerouslySetInnerHTML property and DOMPurify. This is how it looks:

    import DOMPurify from "dompurify";

    const markdown = `
      <h1>How Blockchain is Saving the World</h1>
      <p>
        In his last public speech, <br>
        the <strong>founder</strong> of the popular 
        blockchain network, <br> <em>Vitalic Buterin</em>
        said...
      </p>
    `;
    export default function App() {
      return (
        <div 
          dangerouslySetInnerHTML={
            { __html: DOMPurify.sanitize(markdown) }
          } />
      );
    }

    And here is the result…

    How Blockchain is Saving the World  

    In his last public speech,  

    the founder of the popular blockchain network,  

    Vitalic Buterin said...

    It is worth mentioning that you can use the React dangerouslySetInnerHTML property on any HTML element as seen in the examples below:

    const markdown = `Hello world`;
    export default function App() {
      return (
        <>
          <p dangerouslySetInnerHTML={{ __html: markdown }} />
          <h6 dangerouslySetInnerHTML={{ __html: markdown }} />
          <h5 dangerouslySetInnerHTML={{ __html: markdown }} />
          <h4 dangerouslySetInnerHTML={{ __html: markdown }} />
          <h3 dangerouslySetInnerHTML={{ __html: markdown }} />
          <h2 dangerouslySetInnerHTML={{ __html: markdown }} />
          <h1 dangerouslySetInnerHTML={{ __html: markdown }} />
        </>
      );
    }

    And this is what it looks like on the browser…

    Hello world <p>
    Hello world <H6>
    Hello world <H5>
    Hello world <H4>
    Hello world <H3>
    Hello world <H2>
    Hello world  <H1>

    That’s how to securely use dangerouslySetInnerHTML on a React application…

    For more information about Advantages and importance of react, check out our other blog post why react is ruling the web development industry.

    Looking for a Python language course near me? Unleash your coding potential with Python, the versatile and powerful language that's taking the tech world by storm. Join us and discover the endless possibilities of Python!

    Conclusion

    Here is the conclusion: using the React dangerouslySetInnerHTML is great for rendering HTML markups on-page, especially dynamic ones that can be retrieved from an external API.

    Regardless of the juicy advantages the React dangerouslySetInnerHTML property provides, using it without proper sanitization is as dangerous as its name sounds.

    We recommend that you always use the React dangerouslySetInnerHTML property and a markup sanitizer such as the DOMPurify package.

    I hope this tutorial has shown you some vital information that will help you render static and dynamic markups safely on a page.

    Learn all you need to know about React JS in our react full course at Knowledgehut.

    I’ll see you in the following tutorial…

    Frequently Asked Questions (FAQs)

    1Can you use React dangerouslySetInnerHTML without the wrapper div?

    Yes, dangerouslySetInnerHTML is a property and requires only a HTML element to render.

    2Is it OK to use dangerouslySetInnerHTML?

    Yes, it will help you render markups in ways that the React JSX element will prohibit by default. It will help you pass HTML directly into a component within JSX.

    3What can I use instead of dangerouslySetInnerHTML?

    You can use Vanilla JavaScript to set the innerHTML content of an element to some markup, but this is not recommended.

    4What is sanitization in React?

    This term refers to neutralizing or eliminating potentially malicious codes in an HTML markup.

    5What does dangerouslySetInnerHTML do?

    It enables you to set HTML markup into React JSX components or elements.

    Profile

    Sachin Bhatnagar

    Program Director, FSD

    With 20+ yrs of industry experience in media, entertainment and web tech, Sachin brings expertise in hands-on training and developing forward-thinking, industry-centric curricula. 30k+ students have enrolled in his tech courses.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon