skip to Main Content
const [html, setHtml] = useState<string>("");
<div>
{html ? parse(html):""}
</div>

html is a template with its style but when it renders the other styles of the application override it. i want to prevent that common style of the application should not apply in html content and also html contents style should not apply to other components.

2

Answers


  1. You can use Inline Styling or try You can read about CSS Specificity. Styling on react same as CSS original but if you want use Class just change to ClassName

    Login or Signup to reply.
  2. I also bumped into a similar issue. Restyling each dom node in an HTML template might make things more complicated to maintain in the long run. Changing the global application might also require handling those changes in the HTML markup as well. To make things simple, I created a simple component that uses iframe and renders the markup in isolation making template secure and separated.

    const Webview = function(props) {
      const iFrameRef = useRef();
    
      function resizeIframe() {
        const height = parseInt(iFrameRef.current.contentWindow.document.body.scrollHeight, 10);
        let offset = 32;
        iFrameRef.current.style.height = (height + offset) + "px";
        iFrameRef.current.contentWindow.document.body.style.margin = "0px";
      }
    
      const body = useMemo(() => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(props.body, 'text/html');
        // doc has all the HTML template parsed and stored in memory. you can make changes here before making it available to the iframe 
        return `<!DOCTYPE html>
        <html lang="en" style="overflow:hidden;">
          <head>
              <meta http-equiv="X-UA-Compatible" content="IE=edge" />
              <meta charset="utf-8" />
              <title>Email</title>
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
              <style>
               /* You can also add your global styles here */
                * { 
                  font-family: Roboto,RobotoDraft,Helvetica,Arial,sans-serif;
                }
              </style>
             </head>
             <body>
              ${doc.body.innerHTML}
             </body>
        </html>`
      }, [props.body])
    
      return (
        <iframe
          ref={iFrameRef}
          className={props.className}
          srcDoc={body}
          onLoad={resizeIframe}
        />
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search