const el = useRef();
useEffect(() => {
const onClick = e => {
const dropdown = e.target.closest('.dropdown');
if (dropdown && dropdown !== el.current) {
setIsVisible(false);
}
};
document.addEventListener('click', onClick);
return () => {
document.removeEventListener('click', onClick);
};
}, []);
<div className="dropdown" ref={el}>