How to safely render html in react?

前端 未结 3 1829
温柔的废话
温柔的废话 2020-12-13 18:30

I\'ve got some user generated html markup from a text area and I\'d like to render it on another part of the screen. The markup is saved as a string in the props of the comp

3条回答
  •  我在风中等你
    2020-12-13 19:13

    Sanitize the html using the sanitize-html module, and render the sanitized string using dangerouslySetInnerHTML.

    You can create a simple wrapper component:

    const defaultOptions = {
      allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
      allowedAttributes: {
        'a': [ 'href' ]
      },
      allowedIframeHostnames: ['www.youtube.com']
    };
    
    const sanitize = (dirty, options) => ({
      __html: sanitizeHtml(
        dirty, 
        options: { ...defaultOptions, ...options }
      )
    });
    
    const SanitizeHTML = ({ html, options }) => (
      
    );

    Usage:

    
    

    You can also use react-sanitized-html's SanitizedHTML component, which is a react wrapper around sanitize-html:

    Bing` }
    />
    

提交回复
热议问题