Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

62
Vistas
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);
over 4 years ago · Santiago Trujillo
6 Respuestas
Responde la pregunta

0

Google Analytics 4 is different from pre ga 4. react-ga does not support this yet. https://github.com/react-ga/react-ga/issues/460

You may need to do this manually https://support.google.com/analytics/answer/9325020 https://developers.google.com/analytics/devguides/collection/ga4/tag-guide

over 4 years ago · Santiago Trujillo Denunciar

0

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

over 4 years ago · Santiago Trujillo Denunciar

0

.. 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().then().catch()

Thanks to the comments, I updated this post a little. I added a try/catch (for preventing AddBlocker Crashes) and a setTimeout. The ".catch()"-Methode should be trailed to "ga4react.initialize()" to handle errors inside the initialize promise. 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().catch(err => console.error(err));
  }, 4000);
} catch (err) {
      console.error(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/

over 4 years ago · Santiago Trujillo Denunciar

0

There are 2 versions of google analytics

  1. Google Analytics 4 ( the updated one )
  2. Universal Analytics ( the older one )

react-ga works fine with Universal Analytics as it takes the Tracking Id to initialize the connection between react and google analytics.

The problem is that whenever a user creates a new account, GA4 is being offered by default. But the GA4 doesn't have the Tracking Id that is required. GA4 has the Measurement ID but the react-ga doesn't want it. So we need the Tracking Id in order to set up the react-ga in our react app.

So the solution is, "Either downgrade from GA4 to Universal Analytics or Create a property that contains both of them as in GA4 and Universal Analytics together."

I would recommend watching the following videos:

GA4 vs Universal Analytics: https://www.youtube.com/watch?v=Y6WxUEk6clw

How to downgrade or keep both: https://www.youtube.com/watch?v=jRmb0jMNUKU

over 4 years ago · Santiago Trujillo Denunciar

0

You may want to have a look at this package: https://www.npmjs.com/package/react-ga4

It offers the same API as the normal react-ga. So just change your package name from react-ga to react-ga4 and it should work.

Tried it myself and it works great!

over 4 years ago · Santiago Trujillo Denunciar

0

react-ga does not work with GA-4. I will also say that in react-ga's issues, the owner has said that unless someone creates a PR, he does not intend to add GA-4 support. The project is also not well maintained anymore.

You could theoretically create a universal property in the GA admin dashboard for backwards compatibility with earlier GA versions. At that point, you could use react-ga, but your best bet is to use ga-4-react instead: https://github.com/unrealmanu/ga-4-react

npm i ga-4-react

...

I will add on to @TG___ 's answer. The code he provided in his answer is a good start, but I will mention that it typically crashes the app if someone has an adblocker (adblocker blocks analytics request endpoints, no error handling, etc).

ERROR: Loading failed for the with source “https://www.google-analytics.com/analytics.js”

... Below is an expansion of his code to use the promise that ga4react.initialize() returns. This way, you can essentially detect whether the script didn't load and hence derive if the user has an adblocker that's preventing the GA script from loading. In my example code, I just ignore it and load the app... in other scenarios, I suppose you could invoke a modal to tell them to disable it (of course, that would come with extra code).

By adding

 await ga4react.initialize()

to your index.js in src GA-4 will start and add a pageview. Works also with react-router without adding any code. By the Promise (await) you have to wrap it into an async-function (below as a closure).


import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

const ga4react = new GA4React("G-XXXXXXXXXX");

(async _ => {
  
await ga4react.initialize()
.then(res => console.log("Analytics Success."))
.catch(err => console.log("Analytics Failure."))
.finally(() => {
  ReactDOM.render(
    <React.StrictMode>
      <Router>
        <App />
      </Router>
    </React.StrictMode>,
    document.getElementById('root')
  );
});
})();

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda