Setup Google Analytics to track your React.js website within minutes.

For simplicity of this tutorial, I will pick up where I left in my last tutorial where we created a React-app call go-go-cloud and hosted it on Google Cloud. Here, we will be looking at how to integrate analytics from Google using an open source library from Github call React-GA.

Firstly, head over to our Google Analytics Dashboard to do some setup. Go to the Admin Tab and click Create Account.

Fill in the respective fields, depending on the app you created in the previously tutorial, or any website you are intending to track, just paste the appropriate URL here.

Then you should be brought to Tracking-Code page where you will be shown whats your unique tracking code (i.e. UA-123456789–1)

That is really all you need to do to setup your dashboard!

Now lets get started with the integration of React-GA! Head to your terminal and lets install the package by following the same instructions given in their Github website.

npm install react-ga --save

If you use bower, just replace npmwith bower. That’s all you need to do!

Head over to your App.js and insert this line of import statement at the top of the file.

import ReactGA from 'react-ga';

Then in the same file lets create a function to initialise the ReactGA with your tracking code so GA knows which collector to push the data to:

function initializeReactGA() {
ReactGA.initialize('UA-123791717-1');
ReactGA.pageview('/homepage');
}

Here we initialise GA using tracking code in line 1, then we ask GA to track user’s visit when the component first loaded by naming the view data as /homepage. With GA’s real time tracking technology, let’s see it in action!

Going back to the dashboard, in the right menu panel, 
Choose Real-Time -> Overview and you will be greeted with a data collected depicting that one user is active! And that’s non other than yourself!

You can continue to explore other ways of tracking like when user hit a button or when using click a link. These are call Events and they can be tracked in this manner:

ReactGA.event({
category: 'User',
action: 'Create an Account'
});

They can then be tracked here:

Conclusion

Analytics play a very important part in the online services we created nowadays as they will help us build better softwares, to know what users really use, to understand users’ flows. I hope that with his tutorial, you have now a stepping stone to move forward and build a great analytical ecosystem in your softwares!