Can React Helmet inject a javascript object into <HEAD> tag?

axel picture axel · Jun 20, 2016 · Viewed 21k times · Source

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

Answer

davnicwil picture davnicwil · Jul 20, 2017

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" }' 
  }]} 
/>