Mark Thomas Miller's logo

How to use Google Analytics with React Router v4

June 26, 2018

This post will show you how to use Google Analytics with React Router V4 in three easy steps. While you can't just paste in your embed code and be done with it, it's still pretty easy to use Google Analytics in a single page application. This is how I do it:

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

    yarn add react-ga
  2. Initialize react-ga in the top level of your application (where you render to the DOM), and add your Analytics ID to the initializer.

    // index.js
    // ...import React and so on...
    import ReactGA from 'react-ga'
    ReactGA.initialize('YourAnalyticsID') // Add your ID
    ReactDOM.render(<App />, document.getElementById('root'))
  3. In the file where you control your application's routes, listen to your Router's history. I'll explain how this works below.

    // 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, this example is creating an AppRoutes component to hold your application's pages. It triggers a Google 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.

Now, just import AppRoutes into your application and you're done! Congrats, you've integrated Google Analytics with React Router v4.