Search code examples
react-routerreact-router-redux

How to access history.listen in a React component?


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() {...},
});

Solution

  • 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!