Skip to content

Instantly share code, notes, and snippets.

@unigazer
Created February 8, 2021 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unigazer/649b11e17067909c6f1ae4723b654d85 to your computer and use it in GitHub Desktop.
Save unigazer/649b11e17067909c6f1ae4723b654d85 to your computer and use it in GitHub Desktop.
Click outside React with hooks
import useOutsideClick from './useOutsideClick';
export default () => {
useOutsideClick(useRef, () => {
// Update state or whatever
})
return <></>
}
import { useEffect } from 'react';
const useOutsideClick = (ref, cb) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
cb();
}
}
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
}
});
}
export default useOutsideClick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment