Reputation: 2204
How to close react-burger-menu
by clicking outside the menu?
I use: https://github.com/negomi/react-burger-menu
import { slide as Menu } from 'react-burger-menu'
class Example extends React.Component {
showSettings (event) {
event.preventDefault();
.
.
.
}
render () {
return (
<Menu>
<a id="home" className="menu-item" href="/">Home</a>
<a id="about" className="menu-item" href="/about">About</a>
<a id="contact" className="menu-item" href="/contact">Contact</a>
<a onClick={ this.showSettings } className="menu-item--small" href="">Settings</a>
</Menu>
);
}
}
Upvotes: 1
Views: 2729
Reputation: 2397
You will get .bm-overly class from react-burger-menu.
Note: Clicking on this overlay will automatically close the burger menu but you will need to spread the overlay to the entire screen as below
If you are using menu aligning left side:
.bm-overlay {
background: rgba(255, 255, 255, 0.3);
top: 0px;
right: 0px;
}
If you are using menu aligning right side:
.bm-overlay {
background: rgba(255, 255, 255, 0.3);
top: 0px;
left: 0px;
}
Upvotes: 0
Reputation: 2025
Okay. So if you had the same problem I had where using an onClick to change the menus state worked but reloaded the page and you lose that nice transition effect, do this.
Instead of changing the menus state, just click the overlay as if you were closing the menu by clicking back on the page you were on:
let element: HTMLElement = document.getElementsByClassName("bm-overlay")[0] as HTMLElement;
element.click();
This solution might not be future proof in the case that you update the react burger menu and suddenly the 'bm-overlay' doesn't exist anymore but that seems pretty unlikely and this should work every time. This way you can let the menu handle the state of the 'isOpen' all by itself.
Upvotes: 3
Reputation: 44
I am not providing the complete solution. But seem like menu component from react-burger-menu has prop called isOpen. You can actually modify and use it according to your usecase. https://github.com/negomi/react-burger-menu/wiki/FAQ#i-want-to-control-the-open-state-programmatically-but-i-dont-understand-how-to-use-the-isopen-prop
Upvotes: 0