Skip to content

Instantly share code, notes, and snippets.

@nirnejak
Created November 10, 2020 09:26
Show Gist options
  • Save nirnejak/4c95146b3b7775a670360915e827dcb4 to your computer and use it in GitHub Desktop.
Save nirnejak/4c95146b3b7775a670360915e827dcb4 to your computer and use it in GitHub Desktop.
import React from "react"
const useClickOutside = (ref, callback) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
callback()
}
}
React.useEffect(() => {
document.addEventListener("click", handleClick)
return () => {
document.removeEventListener("click", handleClick)
}
})
}
export default useClickOutside
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment