Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useEffect } from 'react';
export function useOutsideClick(containerRef, triggerRef, cb) {
function isOutsideClick(evt) {
if (
(containerRef.current !== null &&
containerRef.current.contains(evt.target)) ||
(triggerRef !== null && triggerRef.current.contains(evt.target))
) {
return cb({
isOutsideClick: false
});
}
return cb({
isOutsideClick: true
});
}
function handleEscape(evt) {
if (evt.code === 'Escape') {
return cb({
isOutsideClick: true
});
}
}
useEffect(() => {
document.addEventListener('click', isOutsideClick);
document.addEventListener('keydown', handleEscape);
return () => {
document.removeEventListener('click', isOutsideClick);
document.removeEventListener('keydown', handleEscape);
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.