Using Google Analytics With React

January 9, 2020

If all you want to do is add the default Google Analytics tracking code to your website with no other special tracking needs, you don’t need to reach for any 3rd party dependencies. All we need to do is add some basic script to the page, but React makes that a little more complicated that plain HTML.

This simple code using dangerouslySetInnerHTML will get you setup quickly:

<script key="ga_script" async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-XX"></script>

<script key="ga_init" dangerouslySetInnerHTML={{__html: `
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-XXXXXX-XX');
`}} />

Don’t forget to change out UA-XXXXXX-XX with your actual Google tracking code property ID in both the script src and the config call.

Note: If you are worried about the name dangerouslySetInnerHTML and lack of XSS protection, don’t be in this case. We are not using any user input here – this is straight hard-coded JavaScript.

This approach works with with plain React.js applications, and also with frameworks like Next.js as well.

If you need something more complicated, or want an easy way to manage it all, then you can add react-ga and use it instead. Just don’t be in the habit of immediately reaching for 3rd party dependencies without thinking through whether or not you actually need it first.


Tags: , , ,

Categories: ,