How to set up Google Analytics 4 for React-Router?

Viewed 4151

I'm trying to set up Google Analytics 4 on my react site. Previously I used react-ga, but this library doesn't support Google Analytics 4 yet. I pasted the GA4 tag directly into the index.html file without an external library. What additional code do I need to add to get GA4 to work with react router?
Thanks in advance!

4 Answers

You can call gtag directly. Just put the global site tag code in your index.html <head>.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX');
</script>

I was facing the same issue today and ended up pulling out the react-ga package and going this route. I saved the withTracker.js piece from the react-ga demo code and modified it like below.

export default function withTracker(WrappedComponent, options = {}) {
    const trackPage = (page) => {
        window.gtag('send', 'page_view', {
            page_location: window.location.href,
            page_path: window.location.pathname            
        });
    };
...

You should be able stop using react-ga and just insert the global script tag in index.html as Cameron mentioned. Keep in mind you'll likely need to ensure that your app is updating both the window.location and document.title for GA4 work as desired.

Google's docs mention:

"When a pageview is sent to Analytics, the default page parameter values are used, unless modified. This means you do not need to modify page_title or page_location parameters if updates to window.location (e.g. via the History API) and document.title are made prior to the event being sent.".

I have a simple single page application and wasn't receiving detailed page view data until I updated the title AND location at each render.

No additional code is needed, just paste that tag into the index.html and Google Analytics will track all your urls.

Related