Created
March 3, 2023 15:31
-
-
Save aparx/2d1b69399b6d556fa71f7fdf49ea8afd to your computer and use it in GitHub Desktop.
useEffect hook that registers document events outside a specific component or its children
This file contains 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 { RefObject, useEffect } from 'react'; | |
export default function useDetectEventOutside< | |
TNode extends Node, | |
TEventType extends keyof DocumentEventMap | |
>( | |
reference: RefObject<TNode>, | |
eventType: TEventType, | |
eventListener: (this: Document, ev: DocumentEventMap[TEventType]) => any | |
) { | |
useEffect(() => { | |
function handle(this: Document, event: DocumentEventMap[TEventType]) { | |
if (!(event.target instanceof Node)) return; | |
if (reference.current && !reference.current.contains(event.target)) | |
return eventListener.call(this, event); | |
} | |
document.addEventListener(eventType, handle); | |
return () => document.removeEventListener(eventType, handle); | |
}, [reference, eventType, eventListener]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment