reactjsgatsbyreact-helmet

Gatsby use custom javascript


So I want to use these scripts in my Gatsby project:

<script src="https://cdn.jsdelivr.net/gh/manucaralmo/GlowCookies@3.1.1/src/glowCookies.min.js"></script>
<script>
  glowCookies.start('en', { 
      style: 1,
      analytics: 'G-FH87DE17XF', 
      facebookPixel: '990955817632355',
      policyLink: 'https://link-to-your-policy.com'
  });
</script>

(from https://github.com/manucaralmo/GlowCookies)

I tried using it with react-helmet:

<Helmet>
  <script src="https://cdn.jsdelivr.net/gh/manucaralmo/GlowCookies@3.1.1/src/glowCookies.min.js"></script>
  <script>
      glowCookies.start('en', { 
          style: 1,
          analytics: 'G-FH87DE17XF', 
          facebookPixel: '990955817632355',
          policyLink: 'https://link-to-your-policy.com'
      });
  </script>
</Helmet>

But I'm receiving this error:

  41:17  error  Parsing error: C:\(...)\layout.js:     
Unexpected token, expected "}" (41:17)

  39 |     <script>
  40 |         glowCookies.start('en', {
> 41 |             style: 1,
     |                  ^
  42 |             analytics: 'G-FH87DE17XF',
  43 |             facebookPixel: '990955817632355',
  44 |             policyLink: 'https://link-to-your-policy.com'

So just adding the first script tag would work, but not creating an instance of it.


Solution

  • It may not be the nicest way to implement custom javascript, but this is what works best for me. So no need for react-helmet, just the use of Gatsbys build in functions:

    gatsby-ssr.js

    export const onRenderBody = ({ setPostBodyComponents }) => {
      setPostBodyComponents([
        <script
          key="https://cdn.jsdelivr.net/gh/manucaralmo/GlowCookies@3.1.1/src/glowCookies.min.js"
          src="https://cdn.jsdelivr.net/gh/manucaralmo/GlowCookies@3.1.1/src/glowCookies.min.js"
          defer
        />,
        <script key="glowCookies.min.js" src="/js/glowCookies.js" defer />,
      ])
    }
    

    /static/js/glowCookies.js

    glowCookies.start('en', {
       style: 1,
       analytics: 'G-FH87DE17XF',
       facebookPixel: '990955817632355',
       policyLink: 'https://link-to-your-policy.com'
    })