Using this https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked i have found my solution to make my dropdown to get close on click of outside anywhere else.
But problem is, i have two similar components of dropdown to get this apply, so when i apply my last dropdown was working properly but not the first one.I can't get this why ? can anyone please help me on this.
this.container = React.createRef();
this.state = {
open: false,
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = (event) => {
if (
this.container.current &&
!this.container.current.contains(event.target)
) {
this.setState({
open: false,
});
}
};
and at my body div,
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown1</div>}
</div>
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown2</div>}
</div>
Or can i use react-foco?
You need to consider below points to get your work done,
Two separate refs for two dropdown containers.
Maintain two different state variables
Need to handle cases in both handleClickoutside and handleButtonClick methods for refs and button click respectively. refer below code