Using Google Analytics in a React Router v4 app

June 2018

I recently added Google Analytics to Everpage, a single page React application using React Router V4. Some people make it seem difficult to use Google Analytics in a single page application, but it doesn’t need to be this way. This is the solution I’m using:

  1. Add react-ga to your project with something like npm or yarn:

    yarn add react-ga
  2. Initialize react-ga in the top level of your application (where you render to the DOM). Make sure to add your Analytics ID to the initializer. For me, this is in index.js:

    // index.js
    import ReactGA from 'react-ga'
    ReactDOM.render(<App />, document.getElementById('root'))
  3. In the file where you control your application’s routes (which I strongly recommend you keep in a separate file), listen to your Router’s history.

    // AppRoutes.jsx
    import React, { Component } from 'react'
    import { Router, Route } from 'react-router-dom'
    import createHistory from 'history/createBrowserHistory'
    import ReactGA from 'react-ga'
    const history = createHistory()
    history.listen(location => {
    	ReactGA.set({ page: location.pathname })
    export default class AppRoutes extends Component {
    	componentDidMount() {
    	render() {
    		return (
    			<Router history={history}>
    					<Route path="/your" component={Your} />
    					<Route path="/pages" component={Pages} />
    					<Route path="/here" component={Here} />

Basically, we’re creating an AppRoutes component to hold your application’s pages. It triggers an Analytics pageview on mount (the “initial visit” to your website). We also give the Router a history so we can listen to it every time the page changes.

Import the AppRoutes component into your application and you’re done!