'How to render specific HTML tags from a text in React?

I have a dynamic text coming from my server with some HTML tags in it. I don't want to "dangerouslySetInnerHTML" because of security reasons and because I only want to allow specific html tags like <i> <b> <strong> <em>. I don't want to allow any other tag to be rendered like for example or

So let's say I have the following string

This is a text with a <b>bold</b> tag and a <strong>strong</strong> tag. It also includes <i>italic</i> and <em>em</em> tags.

If I render this text I want to render it as followed in my HTML:

This is a text with a bold tag and a strong tag. It also includes italic and em tags.



Solution 1:[1]

I fixed this by using the dompurify library and created a reusable component in React.

html-tag-renderer.js

import React from 'react';
import DOMPurify from 'dompurify';
import PropTypes from 'prop-types';

const HTMLTagRenderer = ({ string, allowedTags }) => {
  const cleanHTML = DOMPurify.sanitize(string, { ALLOWED_TAGS: allowedTags });

  return <div dangerouslySetInnerHTML={{ __html: cleanHTML }} />;
};

HTMLTagRenderer.propTypes = {
  string: PropTypes.string.isRequired,
  allowedTags: PropTypes.array.isRequired,
};

export default HTMLTagRenderer;

can be used like:

 <HTMLTagRenderer allowedTags={['b', 'em', 'strong', 'i']} string="This is a text with a <b>bold</b> tag and a <strong>strong</strong> tag. It also includes <i>italic</i> and <em>em</em> tags." />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jim Peeters