Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 868
SpoKaPh Avatar asked Oct 25 '20 03:10

SpoKaPh


People also ask

How to use Google Analytics with react router V4?

This post will show you how to use Google Analytics with React Router V4 in three easy steps. While you can’t just paste in your embed code and be done with it, it’s still pretty easy to use Google Analytics in a single page application. This is how I do it: Add react-gato your project with npm or yarn: yarn add react-ga

How do I add Google Analytics to my react app?

How to Setup and Add Google Analytics to your React App. 1 Step 1. Create an Account. Go to analytics.google.com. 2 Step 2. Create a Property. 3 Step 3. Install Dependencies. 4 Step 4. Setup Analytics Inside Project. 5 Step 5. Record Custom Events. More items

Why react and Google Analytics are the best tools for web analytics?

It is an undeniable fact that React and Google Analytics are one of the most popular tools and libraries among the web-analyst community. Google Analytics is the most widely used web analysis tool, which helps you easily track and retarget your users.

How do I add an analytics component to my router?

Simply add the component within your router (I believe ideally after any routes that would be matched and any Switch components, because the analytics function should not be priority over your site rendering):


1 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            
        });
    };
...
like image 81
cameronjchurch Avatar answered Sep 30 '22 14:09

cameronjchurch