Last active
April 2, 2019 16:32
-
-
Save reecelucas/f5d34529b2c35ae00eae3c0aba181736 to your computer and use it in GitHub Desktop.
React hook to detect when a click happens outside of a specified element
This file contains hidden or 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'; | |
/** | |
* Usage: | |
* useClickOutside(myRef, event => { | |
* console.log(`${event.target} is outside of ${myRef.current}`); | |
* }); | |
*/ | |
export default (elemRef, fn) => { | |
useEffect(() => { | |
const clickOutside = event => { | |
if ( | |
event.target && | |
elemRef && | |
elemRef.current && | |
!elemRef.current.contains(event.target) | |
) { | |
fn(event); | |
} | |
}; | |
document.addEventListener('click', clickOutside, true); | |
return () => { | |
document.removeEventListener('click', clickOutside, true); | |
}; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment