Skip to content

Instantly share code, notes, and snippets.

@zomars
Created May 30, 2022 18:20
Show Gist options
  • Save zomars/4c366a0118a5b7fb391529ab1f27527a to your computer and use it in GitHub Desktop.
Save zomars/4c366a0118a5b7fb391529ab1f27527a to your computer and use it in GitHub Desktop.
Inject raw html comments using React

I know this is a hack but for my use case this allows me to inject arbitrary html inside head tags:

const DangerousRawHtml = ({ html = "" }) => (
  <script dangerouslySetInnerHTML={{ __html: `</script>${html}<script>` }} />
);

Usage:

const EmailHead = ({ title = "" }) => {
  return (
    <head>
      <title>{title}</title>
      <DangerousRawHtml html={`<!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]-->`} />
    </head>
  )
}

The output will leave some empty script tags along the way which is not optimal but it works:

<html>
  <head>
    <title>Title</title>
    <script></script>
    <!--[if !mso]><!-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!--<![endif]-->
    <script></script>
  </head>
  <body></body>
</html>

Also if you're planning to use renderToStaticMarkup, you can do this to cleanup the empty scripts:

ReactDOMServer.renderToStaticMarkup(<MyRootComponent />)
  // Remove `<DangerousRawHtml />` injected scripts
  .replace(/<script><\/script>/g, "")
export const DangerousRawHtml = ({ html = "" }) => (
<script dangerouslySetInnerHTML={{ __html: `</script>${html}<script>` }} />
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment