Search code examples
javascriptreactjsgoogle-analyticsreach-router

Integrate Google Analytics with reach router in React application


I want to integrate Google Analytics to my React application. I am using reach router which makes things more complicated.

If I use Location provider like this then navigate API doesn't work. So if click on any page, page is not rendered

import { Router,createHistory,LocationProvider }from "@reach/router";
import ReactGA from "react-ga";
ReactGA.initialize("G-xxxxxxx");
const history= createHistory(window);
history.listen( window => {
  ReactGA.pageview(window.location.pathname+ window.location.search);
  console.log('page=>',window.location.pathname);
});
<LocationProvider history={history}>
  <Router></Router>
</LocationProvider>

If I use globalHistory google analytics is available only on homepage, no other pages are in statistics

ReactGA.initialize("G-XXXXXXXXXXX");
globalHistory.listen(({ location }) => {
  window.ga('send', 'pageview');
  // or use the new gtag API
  window.gtag('config', 'G-XXXXXXXXXX', {'page_path': location.pathname});
});

Anyone knows how to fix this on first or second way?


Solution

  • It depends on the fact that you are using a Google Analytics 4 Property ID (G-XXXXXXXX), while the React Analytics package in question works for Universal Analytics. I suggest you create a Universal Analytics Property (as shown in following image) and use the relative identifier UA-XXXXXXX-X:

    enter image description here