Google Analytics 4 with React

.. 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/


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