Skip to content

Instantly share code, notes, and snippets.

@mzahor
Last active February 21, 2022 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzahor/8deb94e7976da1aa62478c202795a1a9 to your computer and use it in GitHub Desktop.
Save mzahor/8deb94e7976da1aa62478c202795a1a9 to your computer and use it in GitHub Desktop.
import { useCallback, useEffect } from 'react';
export function useClickOutside(isOpen, ref, onClose) {
const handleOutsideClick = useCallback(
(e) => {
if (!isOpen) return;
const path = e.path || (e.composedPath && e.composedPath());
if (!path.includes(ref.current)) {
onClose();
}
},
[isOpen, onClose, ref]
);
useEffect(() => {
document.body.addEventListener('click', handleOutsideClick);
return () => {
document.body.removeEventListener('click', handleOutsideClick);
};
}, [handleOutsideClick, isOpen]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment