React Router NavLink not triggering history.listen () function
I am trying to implement Google Analytics with a library react-ga
that needs to run on every route change. 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 NavLink
in my application, the route changes and loads the appropriate component, but the function history.listen()
never fires. However, if I use the browser's back / forward functions, it works.
<NavLink to="/account" activeClassName="active">ACCOUNT</NavLink>
How do I listen to route changes triggered NavLink
?
Edit: Further discussion here: https://github.com/react-ga/react-ga/issues/122#issuecomment-316427527
source to share
Use react-router<Route />
component as wrapper for your tracking function - the route is re-rendered on every location change, 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>
)
source to share