Skip to content

Instantly share code, notes, and snippets.

@codemile
Last active December 30, 2021 20:12
Show Gist options
  • Save codemile/19ab6c74adca21344b337d18d7edc002 to your computer and use it in GitHub Desktop.
Save codemile/19ab6c74adca21344b337d18d7edc002 to your computer and use it in GitHub Desktop.
Hook that adds a click listener outside of an element.
import {DependencyList, useCallback, useEffect, useRef} from 'react';
export const useClickOutside = <T extends (...args: any[]) => any>(
cb: T,
dep: DependencyList
) => {
const ref = useRef<HTMLElement>(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
const callback = useCallback(cb, dep);
useEffect(() => {
const listener = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) {
callback(e);
}
};
document.addEventListener('click', listener);
return () => document.removeEventListener('click', listener);
}, [ref, callback]);
return ref;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment