React-router: Why did you get rid of BrowserRouter's onChange

Created on 27 Feb 2017  路  3Comments  路  Source: ReactTraining/react-router

This is more of a design question than an issue. However I feel like this was a pretty neat way of delegating a function to handle global location changes within BrowserRouter.

I am indeed writing this because it would be nice to have a "global" place to do some form of dispatching, in instances like redux or similarly mobx.

It seems like the best way to handle handle location changes is to dispatch something from one of the mount lifecycle methods in react. One might end up with a lot of duplicated code.

Most helpful comment

Ahh thanks. So something like this seems to work

class App extends React.Component {

  componentWillReceiveProps() {
    //dispatch etc here on locationChange using this.props.location.pathname
  }

  render() {
    return (
      <div className="page-container">
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route exact path='/404' component={NotFound} />
          <Redirect from="/*" to='/404' />
        </Switch>
      </div>
    );
  }
}

App.propTypes = {
  location: PropTypes.object.isRequired
}

export default withRouter(App);

would i have to export the component withRouter ?

All 3 comments

How so? You can only mount one child under <Router>, why not have that component use withRouter and on componentWillReceiveProps update the location? That would leave you with only one place where this is happening.

Ahh thanks. So something like this seems to work

class App extends React.Component {

  componentWillReceiveProps() {
    //dispatch etc here on locationChange using this.props.location.pathname
  }

  render() {
    return (
      <div className="page-container">
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route exact path='/404' component={NotFound} />
          <Redirect from="/*" to='/404' />
        </Switch>
      </div>
    );
  }
}

App.propTypes = {
  location: PropTypes.object.isRequired
}

export default withRouter(App);

would i have to export the component withRouter ?

Yes, because the Router just passes through its child without any props added to it. That's the basic idea, though. You're on the right track! :smile:

Was this page helpful?
0 / 5 - 0 ratings