DEV Community

Cover image for Add Google Analytics to a React-based Website
Arifa
Arifa

Posted on

Add Google Analytics to a React-based Website

Google provides a free web analytics service that can be used to analyze details about the visitors on our website.

Tracking ID

  • Firstly, we need to have a Google Analytics Account, Go to Google Analytics. Once you have signed in to your Google account, click Access Google Analytics, and click Sign up.
  • Fill in your account name, website name, website URL, and select an Industry Category and also the Reporting Time Zone.
  • Under Data Sharing Options, check the boxes next to the options that you want.
  • Click Get Tracking ID.

Configuring the React Project

In the project where you want to add google analytics follow these steps:

Install react-ga package

npm install react-ga --save
Enter fullscreen mode Exit fullscreen mode

Initializing GA and Tracking Pageviews:
Add the following snippet of code in your Index.js file

import ReactGA from 'react-ga';
ReactGA.initialize('UA-tracking-id'); // add your tracking id here.
ReactGA.pageview(window.location.pathname + window.location.search);
Enter fullscreen mode Exit fullscreen mode

Deploy the changes.
Now you can view the analytics in Google Analytics account.

Top comments (0)