Created
April 14, 2025 19:18
-
-
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
This file contains hidden or 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
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