Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v4 route onchange event

Is there any way to fire an event when route changes with react router v4. I need to fire a function on every route change. I use BrowserRouter and Switch from react-router-dom on client side in universal react-redux application.

like image 511
Anurag Jain Avatar asked Dec 06 '22 14:12

Anurag Jain


1 Answers

I resolved this by wrapping my application with an additional component. That component is used in a Route so it also has access to the history prop.

<BrowserRouter>
  <Route component={App} />
</BrowserRouter>

The App component subscribes on history changes, so I can do something whenever the route changes:

export class App extends React.Component {
  componentWillMount() {
    const { history } = this.props;
    this.unsubscribeFromHistory = history.listen(this.handleLocationChange);
    this.handleLocationChange(history.location);
  }

  componentWillUnmount() {
    if (this.unsubscribeFromHistory) this.unsubscribeFromHistory();
  }

  handleLocationChange = (location) => {
    // Do something with the location
  }

  render() {
    // Render the rest of the application with its routes
  }
}

Not sure if this is the right way to do it in V4, but I didn't find any other extensibility points on the router itself, so this seems to work instead. Hope that helps.

Edit: Perhaps you could also achieve the same goal by wrapping <Route /> in your own component and using something like componentWillUpdate to detect location changes.

like image 188
Dennis Avatar answered Dec 31 '22 02:12

Dennis