Skip to content

Instantly share code, notes, and snippets.

@suhodolskiy
Created October 31, 2019 09:01
Show Gist options
  • Save suhodolskiy/8e164d1bb27543ad1079f64d0bb83049 to your computer and use it in GitHub Desktop.
Save suhodolskiy/8e164d1bb27543ad1079f64d0bb83049 to your computer and use it in GitHub Desktop.
React Hook: Click Away
function useClickAway(callback) {
const savedCallback = useRef()
const ref = createRef()
function handleClickOutside(event) {
if (ref && ref.current && !ref.current.contains(event.target)) {
savedCallback.current()
}
}
useEffect(
() => {
savedCallback.current = callback
},
[callback]
)
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
})
return ref
}
@suhodolskiy
Copy link
Author

How to use:

function Dropdown() {
  const [dropdownOpen, setDropdownOpen] = useState(false)
  const ref = useClickAway(() => {
    if (dropdownOpen) setDropdownOpen(false)
  })
  return dropdownOpen && <div ref={ref}>Dropdown</div>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment