With react-router-dom, how can I detect when the user navigates to a new page?
I'm currently using "react-router-dom": "^4.2.2" and "react": "^15.6.1". I want to close my mobile navigation menu when the user has selected a new target URL, but I'm having trouble detecting when the route has changed.
Is there a callback I can hook into for react-router-dom? I would like to be able to call code along the lines of location.onChange(() => { this.state.collapsed = true; })
My current code is as follows:
Component:
class Leftnav extends Component {
constructor() {
super();
this.state = {
collapsed: true,
};
}
toggleMenu = () => {
this.setState({
collapsed: !this.state.collapsed,
})
};
render() { ... { */html here/* } ... };
};
Template:
<ul className={"leftnav-collapse " + (this.state.collapsed ? 'collapsed' : '')}>
<li><NavLink to={`/events`} activeClassName="current">Events</NavLink></li>
<li><NavLink to={`/people`} activeClassName="current">People</NavLink></li>
</ul>
Screenshot:
