Last active
May 12, 2025 17:56
-
-
Save Phryxia/2b3f884345261fbd19b95505ced8eabc to your computer and use it in GitHub Desktop.
Simple react hook implementation for detecting click of outside of the given DOM
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 { useCallback, useRef } from 'react' | |
| type MouseEventHandler = (e: MouseEvent) => void | |
| export function useOutsideClickHandler<T extends HTMLElement>( | |
| callback: MouseEventHandler, | |
| ) { | |
| const userCallback = useRef<MouseEventHandler>(() => {}) | |
| userCallback.current = callback | |
| const handlerPair = useRef<MouseEventHandler>(() => {}) | |
| const refInitializer = useCallback((dom: T | null) => { | |
| if (dom) { | |
| handlerPair.current = (e: MouseEvent) => { | |
| if (e.target instanceof Node && !dom.contains(e.target)) { | |
| userCallback.current(e) | |
| } | |
| } | |
| window.addEventListener('click', handlerPair.current) | |
| } else { | |
| window.removeEventListener('click', handlerPair.current) | |
| } | |
| }, []) | |
| return refInitializer | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Pitfall
This doesn't consider actual visual intersection, rather it only takes account of HTML's hierarchy.
Patch Notes
refprops instead ofLegacyRefto handle mount/demount more robustly.e.targetbeing instance ofNodeexplicitly.