import { useEffect } from 'react' ; const useOnClickOutside = ( ref , callback ) : void => { useEffect ( ( ) => { const isOutside = ( target ) => target instanceof Node && ref . current && ! ref . current . contains ( target ) ; const handleClickOutside = ( event ) => { if ( isOutside ( event . target ) ) { callback ( ) ; } } ; const handleKeyPress = ( event ) => { const KEY_ENTER = 13 ; const KEY_ESCAPE = 27 ; if ( event . keyCode === KEY_ESCAPE ) { callback ( ) ; } else if ( event . keyCode === KEY_ENTER && isOutside ( event . target ) ) { callback ( ) ; } } ; document . addEventListener ( 'mousedown' , handleClickOutside ) ; document . addEventListener ( 'keydown' , handleKeyPress ) ; return ( ) => { document . removeEventListener ( 'mousedown' , handleClickOutside ) ; document . removeEventListener ( 'keydown' , handleKeyPress ) ; } ; } , [ ref , callback ] ) ; } ; export default useOnClickOutside ;