Skip to content

Instantly share code, notes, and snippets.

@aparx
Created March 3, 2023 15:31
Show Gist options
  • Save aparx/2d1b69399b6d556fa71f7fdf49ea8afd to your computer and use it in GitHub Desktop.
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
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