4

I am trying to implement Google Analytics using the react-ga library which needs to fire whenever the route changes. I have the following setup in App.js:

import createBrowserHistory from 'history/createBrowserHistory';
...

const history = createBrowserHistory();
history.listen((location) => {
    console.log('ANALYTICS CODE GOES HERE', location);
});

class App extends Component {
    render() {
        return (
            <Provider store={...}>
                <Router history={history}>
                    ....
                </Router>
            </Provider>
        );
    }
}

export default App;

When I click on a NavLink throughout my app, the route changes and loads the appropriate component, but the history.listen() function never fires. However, if I use the browser's back/forward functionality it does fire.

<NavLink to="/account" activeClassName="active">ACCOUNT</NavLink>

How do I listen to route changes triggered by a NavLink?

Edit: further discussion taking place here: https://github.com/react-ga/react-ga/issues/122#issuecomment-316427527

Troy Carlson
  • 2,965
  • 19
  • 26
  • I can't be sure but this sounds like the history isn't being passed down correctly. Which version of ReactRouter are you using? Also which `Router` are you importing? – Simeon Cheeseman May 21 '17 at 21:18

1 Answers1

1

Use a react-router <Route /> component as a wrapper for your tracking function - the route re-renders every time the location changes. For example:

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import ReactGA from 'react-ga'

ReactGA.initialize('UA-00000000-1')

const tracker = ({location}) => {
  // console.log('tracking', location.pathname)
  ReactGA.set({page: location.pathname})
  ReactGA.pageview(location.pathname)
  return null
}

const App = (props) => (
  <Router>
    <div>
      <Route render={tracker} />
      ...
    </div>
  </Router>
)
Greg
  • 9,963
  • 5
  • 43
  • 46