Skip to content

Instantly share code, notes, and snippets.

@dejurin
Created April 14, 2025 19:18
Show Gist options
  • Save dejurin/ce4b52f46f1537bd5b75f7cebed4bc07 to your computer and use it in GitHub Desktop.
Save dejurin/ce4b52f46f1537bd5b75f7cebed4bc07 to your computer and use it in GitHub Desktop.
Custom hook that calls handler when a click is detected outside of the given ref element
import { useEffect } from "preact/hooks";
// Custom hook that calls handler when a click is detected outside of the given ref element
const useOnClickOutside = (
ref: { current: HTMLElement | null },
handler: (event: MouseEvent | TouchEvent) => void
) => {
useEffect(() => {
// Listener that calls handler if click is outside of ref element
const listener = (event: MouseEvent | TouchEvent) => {
// Do nothing if clicking inside the ref element or its children
if (!ref.current || ref.current.contains(event.target as Node)) {
return;
}
handler(event);
};
// Add event listeners for mouse and touch events
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
// Cleanup event listeners on unmount
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
}, [ref, handler]);
};
export default useOnClickOutside;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment