0

I got HTML come from backend and I need to renderer it inside div or whatever works

I sanitize the HTML before show it up

import DOMPurify from "dompurify";

   ......

 var cleanHtml = DOMPurify.sanitize( HtmlPassedFromBackEnd , {
      FORBID_TAGS: ["style"],
    });

then passing sanitized HTML to component <HtmlComponent template={cleanHtml} />

import React from "react";

export default class HtmlComponent extends React.Component {
   
  
    render() {
      return <div dangerouslySetInnerHTML={{__html: this.props.template }}/>
    }
  
  }

it's working fine in most cases but its failed in another example is there anything like webview I can safely render my HTML

enter image description here

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
  • does it break because of CSS? maybe showing it in an iframe can avoid that https://stackoverflow.com/questions/8240101/set-content-of-iframe – diedu Aug 29 '21 at 04:23
  • is it working on Reactjs I havent seen it before ther e – Mina Fawzy Aug 29 '21 at 18:34

1 Answers1

0

I have created a nice component that match iframe thanks to @diedu

import React from "react";
import DOMPurify from "dompurify";
import StyledFrame from "react-styled-frame";
import styled from "styled-components";


const InnerBox = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
`;
export default class HtmlComponent extends React.Component {
   
  
    render() {
      var {template} = this.props
      template  = DOMPurify.sanitize(template, {
        FORBID_TAGS: ["style"],
      });

      return <StyledFrame
      style={{
        width: "100%",
        margin: "0 auto"
      }}
    >
      <InnerBox>
        <div  style={{
                      overflow: "auto",
                      width:"100%"
                    }}
              dangerouslySetInnerHTML={{ __html: template  }} />
      </InnerBox>
    </StyledFrame>
      
    }
  
  }
  
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156