How to add Google Analytics to the React App

Today we’ll show you how to add Google Analytics to the React App.

It’s very easy to integrate google analytics in the multi page application whereas in the single page application, we need to configure it with the routing.

Here, we will use the npm package to track the user behaviour. You will get the following output after adding the GA in the React application.

Demo Application

Output - How to add Google Analytics to the React App - Clue Mediator
Output – How to add Google Analytics to the React App – Clue Mediator

Steps to add Google Analytics to the React App

  1. Create a react application
  2. Add routing
  3. Install npm dependency
  4. Integrate Google Analytics
  5. Output

1. Create a react application

First of all, let’s create a react application using the create-react-app npm package. Run the following command to create the app.

2. Add routing

We need to add the routing in the react application. We will recommend you to check the following article.

Routing in React JS

You may also like to check the React Router v6.

What’s new in React Router v6

After integrating the routing in React, You will find the index.js file as looks like below.

index.js

Let’s try to split this file into two parts as below.

RoutingComponent.js
index.js

3. Install npm dependency

As we discussed, we will use the react-ga npm package to add Google Analytics in the React Application.

Run the following command to install the package.

4. Integrate Google Analytics

Now, we will integrate Google Analytics in the React component. For that, we have to use the withRouter HOC for the RoutingComponent.js component. Check out the following code.

RoutingComponent.js

Let’s initialize Google Analytics from the root file.

index.js

Don’t forget to update the value of the <TRACKING_ID> in the above code that you will find it from here.

5. Output

Run the react application and check the output.

I hope you find this article is helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *