How to set up and use Google Analytics in React Apps

Gustavo Gonzalez
AlturaSoluciones
Published in
2 min readAug 16, 2018

One of our customers asked for two requirements:

  • Use routes for each of the application's views
  • Be able to track the navigation routes using Google Analytics.

React apps are SPA (Single Page Application) that is the reason we don't see any change in the browser's address bar. Usually we saw the same URL.

To be able to meet the first requirement, we use react-router package, this package allow us to navigate in both ReactJS and React Native apps. Also, we can use it for SSR app (Server Side Rendering). In this way, the requirement was meet without issues.

Also the second requirement can be meet in an easy way. The first step is to install react-ga package, it is a wrapper for Google Analytics script.

# Using yarn
yarn add react-ga
# Using npm
npm install react-ga --add

Then, we should import the component and configure.

import ReactGA from 'react-ga';
...
ReactGA.initialize('UA-000000000-0'); // Here we should use our GA id

The next step is to use the different methods to track whatever we want to track, for example, to track a page view we can use something like:

ReactGA.pageview("/here_the_path");

Or to track an event (a click, zoom, create an user), we can use something like:

ReactGA.event({
category: 'User',
action: 'Created account'
});

If we want to automatize the process of tracking each route, we can use listen event from thehistory object with something like:

history.listen(location => ReactGA.pageview(location.pathname));

With this, we ask React Router to handle the tracking for us.

If you like this story clap as many times as you want, and to see similar stories about technology, check our publications and leave us a comment if you have any question.

If you need a team that can help you to implement your ideas in React JS or React Native, feel free to ping us using our website and filling the contact form.

Versión en español

Gustavo
Mail: gustavo@alturasoluciones.com
Twitter: @Aguardientico
LinkedIn: www.linkedin.com/in/gustavoagonzalez
Blog in spanish: http://aguardientech.blogspot.com

--

--

Gustavo Gonzalez
AlturaSoluciones

25+ years in software development. Loves to learn new technologies and share his knowledge with others.