Google Analytics

Analytics in React Js App with Google Analytics

Analytics is very important in modern day applications as it gives the view of the impact of the application, gives hints about required upgrades or updates on the infrastructure and much more.

Google Analytics (GA) gives a lots of tool and data on same. Here we are going to add google analytics in React Js app.

Setup

In index.html file under public folder of our app, add following code inside head tag.

 <script>
        (function (i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
    </script>

Initialization

Now in the our react component, initialize the analytics after the component has mounted. You may add this initialization method at the entry point of your application. We can get the analytics ID from Google Analytics Account

componentDidMount(){
window.ga('create', 'ANALYTICS-ID', 'auto');
}

Tracking

Now to send the tracking record, when user visits the target page or does any targeted event like click or view,  we set the location/event and push to analytics server. For this, we will set the page location and push.

window.ga('set', 'page', url);
window.ga('send', 'pageview');

Here, we first set ‘page‘ type tracking for ‘url‘ value and then send as ‘pageview‘.

We may have to track not just single event or page, so we will create a function for the set and push operation and it to function library so that we can access at any component or location of our page as required.

setPageAndSendToGA = (url) => {
        window.ga('set', 'page', url);
        window.ga('send', 'pageview');
  };

Now we have to call above function whenever any page is visited or any event is fired. So here I will call this function when my route page component is mounted.

import React, {Component} from 'react';
class HomePage extends Component {
componentDidMount(){
if (window.ga) {
let location = this.props.location;
            let url = location.pathname;
            setPageAndSendToGA(url);

            if (location.search.length === 10) {
                let url = location.pathname + location.search;
                this.setPageAndSendToGA(url);
            }
        }
}

render(){
return .......content
}
}

Here, after the component has mounted, we first check if GA has been initialized and then get the current app url/pathname from props and send.

We can also track events like menu click, element click, etc. For that we will send record in below format.

window.ga('send', {
            hitType: 'event',
            eventCategory: 'category name',
            eventAction: 'post click',
            eventLabel: 'tracking label'
        });


Viewing Analytics Data

Now to test our setup is complete, go to your GA account and the start your application and visit any targeted page or fire any targeted event we have set to track. If all the setup has been set properly, you will start getting data in your account.