Skip to content

Instantly share code, notes, and snippets.

@mponizil
Created April 29, 2020 15:55
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 mponizil/64f05d518c6318335e143e0e920345c0 to your computer and use it in GitHub Desktop.
Save mponizil/64f05d518c6318335e143e0e920345c0 to your computer and use it in GitHub Desktop.
import { useRef, useEffect } from 'react';
// Dispatch onClose callback when clicking outside a referenced element or hitting escape.
// Useful for dismissable dropdowns or overlays prompts.
export const useClosable = onClose => {
const ref = useRef();
const handleClick = e => {
if (!ref.current?.contains(e.target)) {
onClose(e);
}
};
const handleKeyUp = e => {
if (e.key === 'Escape') {
onClose(e);
}
};
useEffect(() => {
document.addEventListener('click', handleClick);
document.addEventListener('keyup', handleKeyUp);
return () => {
document.removeEventListener('click', handleClick);
document.removeEventListener('keyup', handleKeyUp);
};
}, []);
return ref;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment