Skip to content

Add Google Analytics to React Project with React Router

Google Analytics is very important for tracking the website visit and testing various experimental changes performance on the website or app. In this article, I will show how to add Google analytics in a react app. Here I am using a project created by Create-React-App with React router v4 or greater.

Install React GA

You will need react-ga library. Open terminal and install it in your project.

npm install react-ga

Setup Google Analytics in App

After that, we need to initialize the Google Analytics (GA) in the application. Our goal here is to track each page user visits on our site. To accomplish this, we will initialize GA in the root component of our project. In this component, we have different pages route inside the switch tag.

So, when the first time root component will load, we can initialize GA, like this:

For Class based component:

import ReactGa from 'react-ga';

class App extends Component {

    componentDidMount() {
        ReactGa.initialize('Your Trace Id');
    }

    render() {
        return(
            <Switch>
                // Your Routes
            </Switch>
        )
    }
}

For Functional components using React hook:

import ReactGa from 'react-ga';

const App = (props) => {

    useEffect(() => {
        ReactGa.initialize('Your Trace Id');
    }, []);

    return(
        <Switch>
            // Your Routes
        </Switch>
    )
}

Now GA is initialized, we need to add code to trace our page for our application. We can track pages using ReactGa.pageview(‘pathname’). So, for each page in react-router, we need to trigger the ReactGa.pageview event. For the class-based component, we will need to add it in componentDidUpdate lifecycle too, as whenever a new page is visited, root component gets updated. So, we can make changes like below:

For Class based component:

import ReactGa from 'react-ga';

class App extends Component {

    componentDidMount() {
        ReactGa.initialize('Your Trace Id');
        ReactGa.pageview(window.location.pathname + window.location.search);
    }

    componentDidUpdate() {
ReactGa.pageview(window.location.pathname + window.location.search);
}

    render() {
        return(
            <Switch>
                // Your Routes
            </Switch>
        )
    }
}

For Functional components using React hook:

import ReactGa from 'react-ga';

const App = (props) => {

    useEffect(() => {
        ReactGa.initialize('Your Trace Id');
        ReactGa.pageview(window.location.pathname + window.location.search);
    }, []);

    return(
        <Switch>
            // Your Routes
        </Switch>
    )
}

After these changes, you can run your app, and you will see it will start tracking all page visits.

As you will continue development of your app, triggering GA events while development will mess up your reports. For that purpose, either you can create two separate GA tracing id, one for production and one for development, or you can make changes to run GA only when app is running in production environment. For that you can check if app is in production environment while initialising GA.

if (!process.env.NODE_ENV || process.env.NODE_ENV != 'development') {
      ReactGa.initialize(config.GoogleAnalyticsId);
      ReactGa.pageview(window.location.pathname + window.location.search);
}

You can further add more features like event tracing in your app. I hope this article will help you setting up Google Analytics in your app.

Thanks.

Be First to Comment

Leave a Reply

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