简体   繁体   中英

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 tag and a strong tag.标签和标签的文本。 It also includes italic and em tags.

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." />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM