google-analyticsreactjsreact-router

How to set up Google Analytics for React-Router?


I'm trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was hoping someone could shed some light on this.

The package I'm looking at is, react-ga.

My render method on my index.js looks like this.

React.render((
<Router history={createBrowserHistory()}>
    <Route path="/" component={App}>
        <IndexRoute component={Home} onLeave={closeHeader}/>
        <Route path="/about" component={About} onLeave={closeHeader}/>
        <Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
        <Route path="/contact-us" component={Contact} onLeave={closeHeader}>
            <Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
        </Route>
        <Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
        <Route path="/feedback" component={Feedback} onLeave={closeHeader} />
    </Route>
    <Route path="*" component={NoMatch} onLeave={closeHeader}/>
</Router>), document.getElementById('root'));

Solution

  • Keep a reference to your history object. i.e.

    import { createBrowserHistory } from 'history';
    
    var history = createBrowserHistory();
    
    ReactDOM.render((
        <Router history={history}>
            [...]
    

    Then add a listener to record each pageview. (This assumes you've already set up the window.ga object in the usual manner.)

    history.listen((location) => {
        window.ga('set', 'page', location.pathname + location.search);
        window.ga('send', 'pageview');
    });