Skip to content

Instantly share code, notes, and snippets.

@sajadabedi
Forked from chrisdhanaraj/useOutsideClick.js
Created July 24, 2019 13:46
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 sajadabedi/dfbf20132a396467268260b049dcf51b to your computer and use it in GitHub Desktop.
Save sajadabedi/dfbf20132a396467268260b049dcf51b to your computer and use it in GitHub Desktop.
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