DEV Community

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

Posted on

2 1

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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay