react-helmet icon indicating copy to clipboard operation
react-helmet copied to clipboard

dangerouslySetInnerHTML not working for script tags

Open melissafzhang opened this issue 4 years ago • 6 comments

Do you want to request a feature or report a bug? Bug

What is the current behavior? I want to be able to run a script in the helmet on the client. However, react-helmet is removing this script tag.

For example:

<Helmet>
        <script
          type="text/javascript"
          dangerouslySetInnerHTML={{
            __html: 'some code',
          }}
       ></script>
</Helmet>

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React and react-helmet. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

What is the expected behavior? Do not remove script tags with dangerouslySetInnerHTML

Which versions of React and react-helmet, and which browser / OS are affected by this issue? Did this work in previous versions of React and/or react-helmet? react-helmet: 5.2.0 react: 16.13.0

melissafzhang avatar Mar 04 '20 22:03 melissafzhang

Very important feature but no replies.....

traffisco avatar Jan 07 '21 09:01 traffisco

actually, you can use it without dangerouslySetInnerHTML

<script type="text/javascript">
          {`console.log('hey')`}
</script>

traffisco avatar Jan 07 '21 09:01 traffisco

thanks @traffisco , I was thinking it may have been the dangerouslySetInnerHTML; this could be an issue we can follow up on.

cwelch5 avatar Jan 07 '21 17:01 cwelch5

@cwelch5 Any updates on this bug? I just encountered it and I can't render the script tag coming from my headless CMS

kb1995 avatar Mar 22 '21 12:03 kb1995

Any updates?

Mikhail-MM avatar Mar 29 '21 18:03 Mikhail-MM

If you have a react node but you can't control how it's created, you can at least mutate it before sending it to helmet

The below worked for me, however, there could be a very good reason that you shouldn't do that


const convertDangerousHtmlToChildren = node => {
  if (node.props && node.props.dangerouslySetInnerHTML) {
    return {
      ...node,
      props: {
        ...node.props,
        dangerouslySetInnerHTML: undefined,
        children: node.props.dangerouslySetInnerHTML.__html,
      },
    };
  }
  return node;
};


<Helmet>
        {convertDangerousHtmlToChildren(<script
          type="text/javascript"
          dangerouslySetInnerHTML={{
            __html: 'some code',
          }}
       ></script>)}
</Helmet>

darraghmckay avatar Apr 02 '21 08:04 darraghmckay