Reputation: 11
So I'm making a website and I made a mobile drawer for my nav links, it opens fine when I click on the button with 3 lines in it and to close it I did a backdrop, but now when I click a link to go to the next page the nav drawer doesn't close, to close it I have to tap on the backdrop screen and I want the drawer to close when I click on a page link.
app.js
state = {
sideDrawerOpen: false
};
drawerToggleClickHandler = () => {
this.setState((prevState) => {
return { sideDrawerOpen: !prevState.sideDrawerOpen };
});
};
backdropClickHandler = () => {
this.setState({ sideDrawerOpen: false });
};
render() {
let backdrop
if (this.state.sideDrawerOpen) {
backdrop = <Backdrop click={this.backdropClickHandler} />
}
return (
<Router>
<div className="App">
<div style={{ height: '100%' }}>
<Toolbar drawerClickHandler={this.drawerToggleClickHandler} />
<SideDrawer show={this.state.sideDrawerOpen} />
{backdrop}
<Route exact path='/' component={Home} />
<Route exact path='/Contact' component={Contact} />
<Route exact path='/Events' component={Events} />
<Route exact path='/About' component={About} />
<Route exact path='/Gallery' component={Gallery} />
</div>
</div>
</Router>
drawer.js
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/About">About</Link></li>
<li><Link to="/Events">Events</Link></li>
<li><Link to="/Gallery">Gallery</Link></li>
<li><Link to="/Contact">Contact</Link></li>
</ul>
</nav>
Upvotes: 1
Views: 754
Reputation: 15695
Your <Router>
is rendered inside the component in app.js
, so changing a page will not trigger an unmount or reset your state. You can, however, detect a page change in componentDidUpdate
, and use that to manually close your drawer:
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location && this.state.sideDrawerOpen) {
this.setState({ sideDrawerOpen: false });
}
}
Additional reading: https://reacttraining.com/react-router/web/api/history/history-is-mutable
Upvotes: 1