React router v4 route onchange event
I solved this by wrapping my application with an additional component. This component is used in Route
, so it also has history
prop access .
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
The component App
subscribes to history changes, so I can do something on every route change:
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 correct way to do it in V4, but I haven't found any other extensibility points on the router itself, so this seems to work. Hope it helps.
Edit: Perhaps you can also achieve the same goal by wrapping <Route />
in your own component and using something like componentWillUpdate
to detect location changes.
source to share
React: v15.x, React Router: v4.x
components / core /App.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';
class LocationListener extends Component {
static contextTypes = {
router: PropTypes.object
};
componentDidMount() {
this.handleLocationChange(this.context.router.history.location);
this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
}
componentWillUnmount() {
this.unlisten();
}
handleLocationChange(location) {
// your staff here
console.log(`- - - location: '${location.pathname}'`);
}
render() {
return this.props.children;
}
}
export class App extends Component {
...
render() {
return (
<BrowserRouter>
<LocationListener>
...
</LocationListener>
</BrowserRouter>
);
}
}
index.js:
import App from 'components/core/App';
render(<App />, document.querySelector('#root'));
source to share