Setup Google Analytics in React Application – React-Ga Tutorial by Example

Adding Google Analytics tracking in React js application we will discuss; In this guide, you will learn how to quickly add Google Analytics tracking code into the React app with a super easy set of steps.

To integrate Google Analytics in single page application like React, we will use the React-GA library package. It is fully compatible with the latest version of React application. Moreover, it provides methods to send any types of tags and traditional key-value tags to Analytics.

We will go through the step by step tutorial to set up GA in the react application. Thereafter we will discuss the various important methods available in the react-ga package module.

Let’s get started!

How to add Google Analytics in React Application?

We will be following these quick steps to set up Google Analytics tracking in React application:

  • Step 1 – Create React App
  • Step 2 – Install React GA Library
  • Step 3 – Add GA Tracking in React App

 

Step 1 – Create React App

To start, let’s create a new React Js application. Execute the following command in the terminal window:

npx create-react-app react-demo-app

Then, move inside the application directory:

cd react-demo-app

Step 2 – Install React GA Library

Now, we will install the React-GA package in the react application. Execute the following npm command at application root:

npm install react-ga

Step 3 – Add GA Tracking in React App

After the React GA is installed you need to import the ReactGA component and call the initializer. Update the App.js file as shown below:

import { Component } from "react";
import "./App.css";
import ReactGA from 'react-ga';

class App extends Component {

  initReactGA = () => {
    ReactGA.initialize('UA-000000-01');
    ReactGA.pageview('test-init-pageview');
  };

  componentDidMount(){
    this.initReactGA();
  }

  render() {
    return (
      <div className="App container">
        <h2>Google Analytics Example</h2>
      </div>
    );
  }
}
export default App;

We are calling the initReactGA() function inside the componentDidMount hook. It will initialize ReactGA with tracking ID and send the page view.

 

Conclusion

We discussed how to quickly start the integration of Google Analytics into the React application. You can check more on the integration of GA events, routing etc on the official documentation and demo application.

 

 

 

Leave a Comment

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