How to access history.listen in a React component?

Andrew Rasmussen picture Andrew Rasmussen · Nov 21, 2016 · Viewed 21.2k times · Source

I have a specific component who would like to be notified every time the user navigates. Is there some way to access the history passed into the router?

<Router history={history}>
   {// ...}
</Router>

Child component:

var Component = React.createClass({
   componentDidMount: function() {
     // history.listen(this.onRouteChange);
   },
   onRouteChange: function() {},
   render: function() {...},
});

Answer

Andrew Rasmussen picture Andrew Rasmussen · Nov 21, 2016

I've noticed that this works:

import { browserHistory } from 'react-router';

var Component = React.createClass({
  componentDidMount: function() {
    browserHistory.listen(this.onRouteChange);
  },
  ...
});

But it seems like I'd want to use the actual history passed into the router rather than blindly using browserHistory. In some instances I pass in hashHistory instead. Would still appreciate a better solution!