I have a demo App and want to close the drop-down when click anywhere outside.
Just a simple code.
Here is my demo app link of codesandbox
CodePudding user response:
useEffect(() => {
const checkIfClickedOutside = e => {
if (toggle && dropDownRef.current && !dropDownRef.current.contains(e.target)) {
setToggle(false)
}
}
document.addEventListener("mousedown", checkIfClickedOutside)
return () => {
document.removeEventListener("mousedown", checkIfClickedOutside)
}
}, [toggle])