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.
Save React-GA Module as a Dependency
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
Import Module
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
Trigger Page Views
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.
Custom Events
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!
This was really helpful. Thank you very much!
I really live the React way of reusable components 🙂
Thanks for sharing!
It will be really useful on my webpage
Thanks very helpful!
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.
Its very informative for our development company. Thank you for sharing.
What about retrieving the view count data from GA to display it in the app ?
this is very helpful and useful for me.thanks
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
Amazing blog, I am also learning SEO so these points are really helpful for me.Points are really well explain and easily understandable.
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?
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 ?
https://stackoverflow.com/questions/49398355/google-analytics-on-react-app-doesnt-work
Is this a valid translation gtag() to ReactGA.event?
gtag(‘event’, ‘conversion’, {
‘allow_custom_scripts’: true,
‘send_to’: ‘DC-XXXXXXX/sheduspr/sheds0+standard’
});
ReactGA.initialize(‘DC-XXXXXXX’);
ReactGA.event({‘event’: ‘conversion’,
‘allow_custom_scripts’: true,
‘send_to’: ‘DC-XXXXXXX/sheduspr/sheds0+standard’
});
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.
This was helpful article by you.
Thanks for sharing your knowledge with us.
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.
NIce blog Tips, Thank You for sharing
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
Thank you for sharing this post. It is helpful.