Created
April 29, 2020 15:55
-
-
Save mponizil/64f05d518c6318335e143e0e920345c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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