Created
February 28, 2019 16:44
-
-
Save chrisdhanaraj/97d7019ea34ec817a008dc7ec75f3e26 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 { 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