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() {

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

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() {
            category: 'Navigation',
            action: 'Clicked Link',
    render() {

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

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.


  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.

  6. What about retrieving the view count data from GA to display it in the app ?

  7. this is very helpful and useful for me.thanks

  8. Good point, though the other recommended option would be using Google Tag Manager especially if you have multiple TLDs. Plus any other scripts will be with GTM so you will have your clean React Code kept clean

  9. Amazing blog, I am also learning SEO so these points are really helpful for me.Points are really well explain and easily understandable.

  10. Good stuff, thanks for sharing! I have a question, though: is it automatically disabled in ‘development’ profile or do you have to check for it each time?

  11. Hey, I followed this article and configured Google Analytics in my app which I’ve hosted on github. But Google Analytics doesn’t work on it.

    Can you please look into this and give me some insight ?

  12. Is this a valid translation gtag() to ReactGA.event?
    gtag(‘event’, ‘conversion’, {
    ‘allow_custom_scripts’: true,
    ‘send_to’: ‘DC-XXXXXXX/sheduspr/sheds0+standard’
    ReactGA.event({‘event’: ‘conversion’,
    ‘allow_custom_scripts’: true,
    ‘send_to’: ‘DC-XXXXXXX/sheduspr/sheds0+standard’

  13. Thanks for sharing this guide for Google analytics implementation on react application. Google analytics has so much contained in itself that every time you go to explore anything, you will get to know 3-4 additional areas to explore and to do R&D. Being a huge fan of Google Analytics, I love it’s features and quantitative data that I can use for further advancement of my website promotion strategy.

  14. This was helpful article by you.
    Thanks for sharing your knowledge with us.

  15. It is a very advantageous post for me. I’ve enjoyed reading the post. It is very supportive and useful post. Thanks for sharing this so interesting post! I really want to be thankful for the way you have put it here.

  16. NIce blog Tips, Thank You for sharing

  17. Great post!! I have a question though. How to use reactga.initiliasize when track id is fetched from a server. I’m trying it inside a function but i get an error that cannot read property parentNode of undefined

  18. Thank you for sharing this post. It is helpful.

  19. How do you set up analytics for page load time?

  20. Thanks for the very useful tips. Every point is important. big fan, thank you!

  21. Nice post, very informative article.

  22. thank you, helped a lot

  23. Decipher Zone Softwares is a leading outsourcing Java development company which specializes in Website, Java development, Java web application development, blockchain development where trailblazing customizable software solutions are developed with agile methodology at unbelievably low cost.

  24. Thank you! Short, easy and very helpful!

  25. > Just last week I was the developer sitting in “that” meeting realizing I needed to add tracking to a React based application in record time.

    Well, I have exciting news to share with you! 😉 At Segment, we just recently open sourced our React quickstart guide. You can track page visits with react-router and user behavior all within React components using a single API. Here is an example of tracking a User Signup click using an event handler:

    export default class SignupButton extends Component {
    trackEvent() {‘User Signup’);

    render() {
    return (

    Signup with Segment today!


    I’m the maintainer of I recommend checking it out if you want to be able to integrate into any other analytics tool (we support over 250+ destinations) – without writing any additional code.

This post currently has 27 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 *