ReactGA: Google Analytics In React
May 25, 2020
Google Analytics is a great tool for any website to get an understanding of what’s being seen and who’s using it. But in React things can work a little differently sometimes, but with the right tools implementing Google Analytics can be easy and even quick with the right app setup.
When it comes to Google Analytics in React you have a few options, but we’re going to focus on the option that fits best with React.
Enter React GA
React GA is simply a wrapper around Googles own JavaScript API for Google Analytics, but it’s been formatted to easily be added to a React application in just a few lines of code. But it also adds some easily readable flexibility for tracking things the way you write them in React, tracking component opens, not just urls.
To start npm install
npm install react-ga
Then in the root of your application
import ReactGA from ‘react-ga’
ReactGA.initialize(‘Your Google Analytics Id’)
It’s important to put this in the highest level component that makes sense in your app. Usually app.js or index.js, since every page tracking function call needs to happen after this.
Then to track a page you can use the pageView function.
ReactGA.pageview(‘yourUrl’)
If your pages are represented well by the url in the browser you can save a lot of time by tracking your pages with that url using the window object.
ReactGA.pageview(window.location.pathname)
If your url doesn’t represent the component you mean to track, which is often the case in any kind of single page application, you can use pageView and pass a url as a string into it. And it can be any url, even a fictional one that represents the component.
But tracking pages isn’t the whole story if you have a complex UI. ReactGA can also track things like modal opens and events. Tracking modals even works just like pageView, by passing a string into the function.
ReactGA.modalview(‘modal-url’)
Tracking events works a little bit differently, but it only has two required values. The first is a category, a top level descriptor. The second is an action.
ReactGA.event({
category:’Store’,
action:’Added to cart’
})
Those are the basics of ReactGA, with that you can track most major things in an application. As always there are more details in the docs, right here.