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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With