I have made a custom dropDown with a div that I set an onClick attribute to open dropDown and close it. but also I want to close it when the user clicks to another part of the site.
<div
onClick={() => setIsDropDownOpen(!isDropDownOpen)}
className="selected-drop-down"
>
<span className="dropDownText">{selectedQuoteCurrency}</span>
<img
className="dropDownIcon"
src={require("../assets/image/arrow/dropDown-Arrow.png")}
width="15px"
alt="arrow"
/>
</div>
I also do this logic
useEffect(() => {
if(isDropDownOpen) {
window.addEventListener('click',changeDD )
}else {
window.removeEventListener('click',changeDD )
}
},[isDropDownOpen])
function changeDD() {
setIsBaseDropDownOpen(false)
}
But I was faced with a problem that when the component didmount for the first time everything is okay and dropDown opened and when click over there it closed, but for the second time, the dropdown didn't open because the state did not change to true.
furthermore, I tried to handle this click event by tabindex attribute according to this document => developerMozila but I didn't succeed
You can use hover in css like this. when mouse go away from loc of dropdown menu, automatic close.
.options:hover{
display: flex;
flex-direction: column;
position: absolute;
}
<div className="options">
<button>Add</button>
<button>Logout</button>
</div>