Created
May 6, 2019 16:41
-
-
Save worc/7ff1e76598c82979a1c2d2df8cefd986 to your computer and use it in GitHub Desktop.
a react hook for binding an event to a click outside an element
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' | |
function clickAwayListener (elementId, callback) { | |
return event => { | |
const outsideClick = !document.getElementById(elementId).contains(event.target) | |
if (outsideClick) { | |
callback() | |
} | |
} | |
} | |
export function useClickAway (elementId, callback) { | |
useEffect(() => { | |
document.addEventListener('click', clickAwayListener(elementId, callback)) | |
return document.removeEventListener('click', clickAwayListener(elementId, callback)) | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment