Created
March 13, 2026 13:13
-
-
Save its-monotype/3a49eb13dd87439c435c90e90baa5297 to your computer and use it in GitHub Desktop.
React hook that detects pointer presses outside elements to close UI like dropdowns or popovers, listening on the document and using event.composedPath() so it works across portals and Shadow DOM where event.target can be misleading due to event retargeting.
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 * as React from 'react'; | |
| export function useOutsidePress( | |
| enabled: boolean, | |
| refs: React.RefObject<HTMLElement | null>[], | |
| onOutsidePress: () => void, | |
| ) { | |
| const callbackRef = React.useRef(onOutsidePress); | |
| React.useLayoutEffect(() => { | |
| callbackRef.current = onOutsidePress; | |
| }); | |
| React.useEffect(() => { | |
| if (!enabled) return; | |
| const handler = (event: PointerEvent) => { | |
| const path = event.composedPath(); | |
| const isInside = refs.some( | |
| (ref) => ref.current && path.includes(ref.current), | |
| ); | |
| if (!isInside) callbackRef.current(); | |
| }; | |
| document.addEventListener('pointerdown', handler, true); | |
| return () => document.removeEventListener('pointerdown', handler, true); | |
| }, [enabled, refs]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment