How To Add Google Analytics To React App

In order to improve your website’s functionality, it is crucial to have a thorough understanding of your users and their actions. Google Analytics is widely used for tracking and assessing website traffic. This tutorial will provide step-by-step instructions on how to add Google Analytics to your React application.

Step 1: Getting the Tracking ID

First, you’ll need a Tracking ID from Google Analytics. If you don’t have one, follow these steps:

  1. Go to the Google Analytics website and sign in.
  2. Click on “Admin” at the bottom left corner.
  3. Under the “Account” column, select your account from the dropdown menu.
  4. Under the “Property” column, click on “Tracking Info” and then “Tracking Code”.
  5. Your Tracking ID will be displayed at the top of the page.

Keep this Tracking ID at hand, as we will need it for the next steps.

Step 2: Installing the React-GA Library

We will use the react-ga library to integrate Google Analytics with our React app. You can install it using either npm or Yarn:

    // Using npm
    npm install react-ga

    // Using yarn
    yarn add react-ga
    

Step 3: Initializing and Using React-GA

After installing react-ga, you need to initialize it with your Tracking ID. The ideal place to do this is in the main index.js file where your React app is rendered.

    import ReactGA from 'react-ga';
    ReactGA.initialize('Your-Google-Analytics-Tracking-ID');
    ReactGA.pageview(window.location.pathname + window.location.search);
    

Each time a user visits a page in your application, you need to record it with Google Analytics. This can be done using the pageview method, as shown above. You need to call this method whenever the page route changes.

If you are using React Router, you can do it in your main App component like this:

    import ReactGA from 'react-ga';
    import { BrowserRouter as Router, Route } from 'react-router-dom';

    ReactGA.initialize('Your-Google-Analytics-Tracking-ID');

    function App() {
        useEffect(() => {
            // To Report Page View 
            ReactGA.pageview(window.location.pathname + window.location.search);
        }, []);
        // Your routes here
    }
    

Now Google Analytics is integrated into your React app! You can view the data on the Google Analytics dashboard. Remember it might take up to 24 hours for the data to appear on your Analytics dashboard.

Happy tracking!