Adding Google Analytics to your React Application

Adding any kind of tracking to any project always seems to be an afterthought. Generally just before launching, a stakeholder puts their hand up and states that we need to track everything…. Usually resulting in lots of frustrating mutterings from all developers involved.

The above scenario rings too close to home for me. Just last week I was the developer sitting in “that” meeting realising I needed to add tracking to a React based application in record time. Thankfully, things turned out to be extremely easy. The application I was working on wasn’t too complex and was well structured.

This is how I went about it.

The business I was helping uses Google Analytics for all their tracking needs, so we decided to continue with that.

The project relies heavily on npm, so by running the following command I made sure the React-GA Module was saved as a dependency in the package.json file like so:


npm install react-ga --save

Having now installed React-GA it was time to import the module into the required file and initialise our unique tracking number.


import ReactGA from 'react-ga';`
ReactGA.initialize('UA-XXXXXXXX'); //Unique Google Analytics tracking number

The next step was to trigger page views with each view trigger. In my case, I needed to hook into the React Router onUpdate method and fire a function that looked at the hash of the URL due to the history setting of the router.


function fireTracking() {
    ReactGA.pageview(window.location.hash);
}

<Router onUpdate={fireTracking} history={hashHistory}>
    ...
</Router>

One thing to note is you may need to adjust the window.location argument you push to the ReactGA.pageview() function. It will really depend how you have set up React Router.

All in all, pretty straight forward. Around 5 line of code.

With all tracking, the more metrics, the better. So with the above being extremely quick to implement I sat down with he marketing team to work on integrating custom events for particular actions within the app.

I’ll save you from the finer details but with the above ground work laid, adding a custom Google Analytics Event within the React application went like this:

Call a function (e.g. handleClick()) within an onClick event that fires a custom event.


import React from 'react';
import ReactGA from 'react-ga';
    
export default class SomeComponent extends React.Component {
    
    handleClick() {
        ReactGA.event({
            category: 'Navigation',
            action: 'Clicked Link',
        });
    }
    
    render() {

        return (
            <div>
                <a onClick={()=>{this.handleClick()}}>Link</a>
            </div>
        );
    }
}

Hopefully the above gives you a little insight into how to go about adding custom events within your React components.

It’s quite a trivial example, but opens the door to lots of possibilities.

Happy tracking!

Want to become a better web developer?

Join over 25,000 other developer & designers who get awesome links to the best news and articles each week delivered directly to their inbox.

6 Comments

  1. This was really helpful. Thank you very much!

    I really live the React way of reusable components 🙂

  2. Thanks for sharing!

    It will be really useful on my webpage

  3. Thanks very helpful!

  4. What are benefits of using a wrapper on top of google analytics script? GA is not impacting state or mechanics of the application at all so why to add another level of complication instead of using pure GA code which additionally comes from Google’s CDN?

    • Using a wrapper can be extremely useful in two cases.
      1- If google chooses to update their api. They did so when they moved from ga.js to analytics.js
      2- In case you also want some other 3rd party analytics website to have the same event, you could do so just by adding that API in the wrapper after the GA code.

  5. Its very informative for our development company. Thank you for sharing.

This post currently has 6 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

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