How to add google analytics to react app example?

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

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

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

React is a single-page application, There are multiple ways you can configure it.

  • without router
  • React-router history

Install react-go npm into the 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 use JavaScript.

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

npm i --save react-ga

It updates the dependencies section with the following information in package.json

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

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

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

Tracking is enabled by calling the ReactGA.initialize method with options Optional parameter. Syntax:

ReactGA.initialize(trackingid, OptionsObject);

A tracking Id is a unique id that you get from the Analytics website.

Options Object is a javascript object with key and values/objects.

How to track page views?

to track page views, Need to send the 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 applications, If react-router is configured, you need to add the settings below.

First, install react-router-dom into the application.

 npm install --save react-router-dom history

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

history. listen to fires whenever the 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 a couple of hours to take effect in the google analytics tool.