Created
October 25, 2023 03:57
-
-
Save pirey/f0779c522dcce682beab2457e299add7 to your computer and use it in GitHub Desktop.
event handler outside element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useOutsideAlerter(ref, eventType, callback, childSelector) { | |
useEffect(() => { | |
function handler(event) { | |
if (!ref.current) return; | |
const clickedOutside = childSelector | |
? !Array.from(ref.current.querySelectorAll(childSelector)).some( | |
(node) => node.contains(event.target), | |
) | |
: !ref.current.contains(event.target); | |
if (clickedOutside) { | |
console.log(ref.current); | |
console.log("clicked outside"); | |
callback(event); | |
} | |
} | |
if (Array.isArray(eventType)) { | |
eventType.forEach((type) => { | |
document.addEventListener(type, handler); | |
}); | |
} else { | |
document.addEventListener(eventType, handler); | |
} | |
return () => { | |
if (Array.isArray(eventType)) { | |
eventType.forEach((type) => { | |
document.removeEventListener(type, handler); | |
}); | |
} else { | |
document.removeEventListener(eventType, handler); | |
} | |
}; | |
}, [ref]); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment