How to use Google Analytics with React Router v4
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:
-
Add
react-ga
to your project with npm or yarn:yarn add react-ga
-
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'))
-
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 }) ReactGA.pageview(location.pathname) }) export default class AppRoutes extends Component { componentDidMount() { ReactGA.pageview(window.location.pathname) } render() { return ( <Router history={history}> <div> <Route path="/your" component={Your} /> <Route path="/pages" component={Pages} /> <Route path="/here" component={Here} /> </div> </Router> ) } }
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.