Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {...},
});
like image 875
Andrew Rasmussen Avatar asked Nov 21 '16 20:11

Andrew Rasmussen


Video Answer


2 Answers

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!

like image 179
Andrew Rasmussen Avatar answered Oct 07 '22 01:10

Andrew Rasmussen


Use withRouter from 'react-router' like this:

import React from 'react' 
import PropTypes from 'prop-types' 
import { withRouter } from 'react-router'

Following a simple component that shows the pathname of the current location. Works the same for history prop, just use history instead of location then.

class ShowTheLocation extends React.Component {   
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

Create a new component that is "connected" (to borrow redux // terminology) to the router.

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

From: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

like image 20
Fabian Bosler Avatar answered Oct 07 '22 02:10

Fabian Bosler