class Menu extends Component {
state = { show: false }
toggleMenu = () => {
this.setState({ show: !this.state.show })
}
render() {
const { show } = this.state
return(
<div>
<button onClick={this.toggleMenu}>MENU</button>
{
show
? <ul>
<li>qwe</li>
<li>asd</li>
<li>zxc</li>
</ul>
: undefined
}
</div>
)
}
}
class Menu extends Component {
state = { isActive: false };
wrapper = React.createRef();
componentWillUnmount() {
this.removeOutsideClickListener();
}
addOutsideClickListener() {
document.addEventListener('click', this.handleDocumentClick);
}
removeOutsideClickListener() {
document.removeEventListener('click', this.handleDocumentClick);
}
onShow() {
this.addOutsideClickListener();
}
onHide() {
this.removeOutsideClickListender();
}
onClickOutside() {
this.setState({ isActive: false });
}
handleDocumentClick = e => {
if (this.wrapper.current && !this.wrapper.current.contains(e.target)) {
this.onClickOutside();
}
};
toggleMenu = () => {
this.setState(
prevState => ({ isActive: !prevState.isActive }),
() => {
this.state.isActive ? this.onShow() : this.onHide();
},
);
};
render() {
const { isActive } = this.state;
return(
<div ref={this.wrapper}>
<button onClick={this.toggleMenu}>MENU</button>
{isActive && (
<ul>
<li>qwe</li>
<li>asd</li>
<li>zxc</li>
</ul>
)}
</div>
)
}
}