Google Analytics 4 with React Google Analytics 4 with React reactjs reactjs

Google Analytics 4 with React


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


.. react-ga does not work with Google Analytics 4.

Use ga-4-react instead: https://github.com/unrealmanu/ga-4-react

npm i ga-4-react

By adding

import GA4React from "ga-4-react";const ga4react = new GA4React("G-XXXXXXXXXX");ga4react.initialize()

Thanks to the comments, I updated this post a little. I added a try/catch (for preventing AddBlocker Crashes) and a setTimeout.Analytics Systems should not be loaded at the beginning of a Page load. React apps are mostly single page applications, so this code is only loaded once (if needed you can replace "4000" milliseconds to "0").

import React from "react";import ReactDOM from "react-dom";import App from "./App";import GA4React from "ga-4-react";ReactDOM.render(<App />, document.getElementById("root"));try {  setTimeout(_ => {    const ga4react = new GA4React("G-XXXXXXXXXX");    ga4react.initialize();  }, 4000);} catch (err) {}// G-XXXXXXXXXX is your MESS-ID from Google Analytics 

How to find the MESS-ID in Google Analytics 4 (new) properties =>https://analyticshelp.io/blog/google-analytics-property-tracking-id/