web-development top banner

Using dangerouslySetInnerHTML - Getting Started with DOM 

Read it in 9 Mins

Last updated on
07th Jun, 2022
Published
12nd May, 2022
Views
5,689
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.

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)

1. Can you use React dangerouslySetInnerHTML without the wrapper div?

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

2. Is 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.

3. What 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.

4. What is sanitization in React?

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

5. What does dangerouslySetInnerHTML do?

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

Profile

KnowledgeHut

Author
KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.