How to safely Rendering Raw HTML content in React

How to safely Rendering Raw HTML content in React

·

2 min read

Multi-tenant (4).png

React having the build-in method ( dangerouslySetInnerHTML ) for rendering the raw HTML content inside the React App. But the problem is that method is not safe to use.

In real-world, we need to render the raw HTML like e-mail content, rich text editor content etc.

In-order to safely render that method we need to Sanitize those HTML, which basically removes the untrusted codes.

By using sanitize-html we can safely render the HTML inside the react app.

Screenshot 2020-09-06 at 11.40.04 PM.png

The sanitize-html return the sanitized HTML content, like

const sanitizeHtml = require('sanitize-html');
const untrustedCode = `<img src=x onerror=alert('img') />`;
const options = {}; // Optional
const trustedCodes = sanitizeHtml(untrustedCode, options);

In order to use these on the react app, we need to use the dangerouslySetInnerHTML method.

import React from "react";
import sanitize from "sanitize-html";

const SanitizedHTML = ({ html, options }) => {
  const defaultOptions = {
    allowedTags: ["b", "i", "em", "strong", "a"],
  };
  const sanitizeOptions = {
    ...defaultOptions,
    ...options,
  };

  const trustedCode = sanitize(html, sanitizeOptions);
  return <div dangerouslySetInnerHTML={{ __html: trustedCode }}></div>;
};


export default SanitizedHTML;

Now we can use this component like these

import React from "react";

const MailContent = () => {
  const mailContnent = `<script>alert('hello world')</script>`;

  return <SanitizedHTML html={mailContnent} />;
};

export default MailContent;

How do we trust that this HTML is safer to use?

We can monitor the sanitize-html vulnerabilities and constantly update the latest version will keep your application safe.

Like, embed the vulnerabilities scanner report on the readme file is one of the best ways to monitor your dependencies vulnerabilities.

Known Vulnerabilities