react
GA4 Analytics

https://www.npmjs.com/package/ga-4-react

 

GA4React – Google Analytics 4 React

Simple wrapper of ga4 scripts for React: https://developers.google.com/analytics/devguides/collection/ga4

Google Analytics 4 React

Example without components

const ga4react = new GA4React(
'YOUR GA CODE',
{ /* ga custom config, optional */ },
[ /* additional code, optional */ ],
5000 /* timeout, optional, defaults is 5000 */,
options /* { nonce: ['first-script-is-async','second-script'] } */

});
ga4react.initialize().then((ga4) => {
  ga4.pageview('path')
  ga4.gtag('event','pageview','path') // or your custom gtag event
},(err) => {
  console.error(err)
})

Inject GA4React function in props of childrens

Example with custom components 'GA4R'

const Test: React.FC<any> = ({ ga4 }) => {
  return <>{ga4 && console.log(ga4)}</>;
};


<GA4R code="YOUR GA CODE">
    <Test></Test>
</GA4R>

RENDER:

console.log results:

{pageview: ƒ, gtag: ƒ, event: ƒ}

Components withTracker

Pass pageview data to the path prop:

const Tracker = withTracker(props => <>{JSON.stringify(props)}</>);
...
 <Tracker path="myCustomPath" gaCode="GA-CODE"></Tracker>

useGA4React Hook

const Example = () => {
  const ga4React = useGA4React(); // GA CODE, optional, if empty try to get from globals
  return <>{JSON.stringify(ga4React)}</>;
};

"Manual start"

import React from "react";
import ReactDOM from "react-dom";
import GA4React, { useGA4React } from "ga-4-react";

const ga4react = new GA4React("G-1JXXXXX");

function MyApp() {
  const ga = useGA4React();
  console.log(ga);

  return <div className="App">hi!</div>;
}

(async () => {
  await ga4react.initialize();

  ReactDOM.render(
    <React.StrictMode>
      <MyApp />
    </React.StrictMode>,
    document.getElementById("root")
  );
})();

 

 

 


 

 

Google Analytics 4 with React

I've been trying to use react-ga package with google analytics 4 in my app. The measurement id doesn't work with it and there is no tracking code in google analytics 4 I can use. Please, I need help!

import ReactGA from 'react-ga';
const trackingId = 'G-XXXXXXXXXX'; // UA-XXXXXXXXX-X isn't available in GA4
ReactGA.initialize(trackingId, options);
ReactGA.pageview(page);

reactjsgoogle-analyticsgoogle-analytics-apireact-gaga4

The code you entered in the example, G-XXXXXXXXXX, refers to the new Google Analytics 4 which, being a different system from the previous one and does not work (yet) with that plugin.

So you can follow the instructions mentioned in the answer of @Shyam or (and I suggest you because GA4 is too unripe at the moment) create a Universal Analytics type Property and use its ID (UA-XXXXX-X) with the plugin you indicated. You can find it by clicking on Show advanced options (when you create a new property):

enter image description here

 

Currently there aren't API or SDK for GA4. – Michele Pisani Nov 2 '20 at 12:24


https://medium.com/finnovate-io/integrating-google-tag-manager-with-a-react-app-5a8584ee2251

Integrating Google Tag Manager with a React App

 

 

Google Tag Manager is a great tool, it allows you to integrate third party data collection and analytics tools with your web site without modifying code. However, integrating with Tag Manager can be a bit of a mystery in the context of a Single Page Application, like one written in React.js.

You can’t just copy and paste a code snippet and expect everything to work

Upon setting up Tag Manager, it tells you to insert a couple of JavaScript snippets into *every* page of your website. Something along the lines of:

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager --><!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

But in a Single Page Application, there is really only one page, so do we just copy and paste this into index.html and call it a day?

Keep everything in JavaScript

While you can certainly just paste the supplied code snippets into the index.html file of your application, there are certain upsides to keeping code inside JavaScript files. For one, we use different GTM ID’s for different build environments. Keeping code inside JavaScript files and index.html to a bare minimum allows us to easily configure deployment bundles for different target environments.

We decided to use react-gtm-module (https://github.com/alinemorelli/react-gtm). We simply add the following code inside the JS file that mounts our App component to index.html and react-gtm-module injects the tag manager code in the right places. Note that the GTM ID can be a configuration variable from your build process.

import TagManager from 'react-gtm-module'

const tagManagerArgs = {
    gtmId: 'GTM-XXXXXX'
}

TagManager.initialize(tagManagerArgs)

Set a History Change trigger in your Tag Manager container

Since your tag manager code snippet sits inside of index.html the whole time, you will need to set a *History Change trigger* inside your Google Tag Manager workspace to detect route changes in your single page application:

 

img

With the History Change trigger in place, you can add new Tags and fire them based on the History Change trigger:

img

Don’t forget to publish your workspace

Once you are done setting up your triggers and tags, don’t forget to publish your workspace container. Otherwise, your website will get a 404 error when it tries to access your Tag Manager instance.

Finnovate.io is a technology company focused on helping organizations build unique digital experiences on web, mobile and blockchain. Finnovate.io offers development services, training, consulting, as well as a platform that rapidly turn paper based content into interactive experiences.

 

Scroll to Top