1

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/>
});
Dave S
  • 788
  • 1
  • 11
  • 30
  • This question might be duplicated try this https://stackoverflow.com/questions/32553158/detect-click-outside-react-component – dorriz Apr 09 '19 at 11:39

2 Answers2

1

I followed the article from the link below and it works.

https://medium.com/@pitipatdop/little-neat-trick-to-capture-click-outside-react-component-5604830beb7f

0

i think this may help..

In Sidebar component use onMouseOver||onMouseLeave

Sidebar comp

closeSidebar=()=>{
this.setState({show:false})
}

return(
<div  onMouseLeave={this.closeSidebar} >sidebar</div>
)
export default Sidebar
Sukesh
  • 184
  • 2
  • 17