I want to close side panel when i click anywhere else in the document.
I have a side panel which will open on clicking a button and close on clicking on the same button. However, i want to close sidepanel even when clicking anywhere else in the document.
I have tried using document.addeventlistener('mousedown', handle_toggle)
which works, but it will close the sidepanel even when I click on the sidepanel itself.
How can i fix it such that it will not close on clicking sidepanel?
Below is the code:
this.state = {
side_panel_open: false,
};
componentDidUpdate () {
if(this.state.side_panel_open) {
document.addEventListener('mousedown',this.toggle_side_panel);
}
}
handle_btn_click = () => {
this.setState({side_panel_open: !side_panel_open});
}
toggle_side_panel = () => {
this.setState({side_panel_open: false});
}
return (
<button onClick={this.handle_btn_click}>
click me
</button>
{this.state.side_panel_open &&
<Sidepanel/>
});