21

I've a question, I need to inject into the HEAD tag a javascript object, for tag management purposes. This is my Helmet component, but it accepts only specific parameters to set to metadata serverside through rewind() function.

Is there a way still to use React Helmet to do what I need, so, create javascritpt objects into a SCRIPT tag or should I follow a different approach?

MyComponent.js

<Helmet
    title={article.get('title')}
    meta={[
        {"property": "og:title", "content": article.get('title')},
        {"property": "og:url", "content": article.get('url')},

        {"property": "twitter:title", "content": article.get('title')}
    ]}
/>

server.js

let htmlHead = `
  ${head.title}
  ${head.meta.toString()}
`;

Thank you for the support

axel
  • 3,778
  • 4
  • 45
  • 72

4 Answers4

23

Th existing answers are outdated. You don't need to contort the code with script attributes or innerHTML. You can use the <script> tag as usual in HTML:

<Helmet>
  <script src="https://some.host/api.js" type="text/javascript" />
</Helmet>
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
18

Update

This answer from 2017 applies for v3 of react-helmet, and is now a little outdated - there's now a better way to do this, using a script tag directly, as referenced in a newer answer, which I'd recommend doing instead.

Will keep this answer up for posterity, and for people on older versions of Helmet. But just a note that though it's the top voted answer, it's no longer the best answer.


I need to inject into the HEAD tag a javascript object

You could define the object in an inline script, using the innerHTML attribute on Helmet's script prop - this attribute was introduced in Helmet 3.0.0

<Helmet 
  script={[{ 
    type: 'text/javascript', 
    innerHTML: 'window.yourObject = { it: "works" }' 
  }]} 
/>
davnicwil
  • 28,487
  • 16
  • 107
  • 123
12

If I understood your question correctly, in your <Helmet/> declaration, you can add in a script property to inject a <script> tag into the HTML head of your pages.

<Helmet
    title={article.get('title')}
    meta={[
        {"property": "og:title", "content": article.get('title')},
        {"property": "og:url", "content": article.get('url')},

        {"property": "twitter:title", "content": article.get('title')}
    ]}
    script={[
            {"src": "http://url.com/script.js", "type": "text/javascript"}
    ]}
/>
Carven
  • 14,988
  • 29
  • 118
  • 161
3

Just add a script tag in following way:

<Helmet>
    <script type="text/javascript">
        {`console.log("Hello World");window.secret = "Tss..."`}
    </script>
</Helmet>
zemil
  • 3,235
  • 2
  • 24
  • 33