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.
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:
Most helpful comment
Ahh thanks. So something like this seems to work
would i have to export the component
withRouter?