Skip to content

Instantly share code, notes, and snippets.

@pirey
Created October 25, 2023 03:57
Show Gist options
  • Save pirey/f0779c522dcce682beab2457e299add7 to your computer and use it in GitHub Desktop.
Save pirey/f0779c522dcce682beab2457e299add7 to your computer and use it in GitHub Desktop.
event handler outside element
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