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')
);
});
})();