How to add google analytics to react app with example?


This post talks about add or setup google analytics in react application.

Google analytics is a service from google to track pages, visitors and session information of an website. It is free to use in any website.

First, Get tracking id from google analytics site. The simple tracking id format is UA-000000-00.

React is a single page applications, There are multiple ways you can config

  • without router
  • React-router history

Install react-go npm into application

react-ga is a google analytics module for javascript to integrate into websites or applications. We can integrate into Angular or Vuejs or any other applications that uses JavaScript.

install react-ga package into existing application using npm command.

npm i --save react-ga

This will update the dependencies section with following information in package.json

"dependencies": {
    "react-ga": "3.3",
  }

In index.js or main component, Please add the following

import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-00');

Tracking enabled by calling ReactGA.initialize method with options optional parameter. Syntax:

ReactGA.initialize(trackingid,OptionsObject);

Tracking Id is unique id which you get it from Analytics website.

Options Object is an javascript object with key and values/objects

How to track page views?

to track page views, Need to send page page name

ReactGA.pageview('about');

The same can be rewritten using useHook in react

 useEffect(() => {
    ReactGA.initialize('GA-000000-01');
    ReactGA.pageview(window.location.pathname);
  })

Adding google analytics to react-router

In bigger application, If react-router is configured, you need to add the settings below

First install react-router-dom into application

 npm install --save react-router-dom history

once react-router-dom and history is installed, you can add history with listening the pageview event with below code

history.listen fires whenever router changes its path, This will track the page views from one path to another.

  const history = createBrowserHistory();

history.listen((location) => {
    ReactGA.initialize('GA-000000-01');
    ReactGA.set({ page: location.pathname });
    ReactGA.pageview(location.pathname)
  }
);

Once all the required changes, It will take couple of hours to take effect in google analytics tool.

Similar Posts