Skip to content

Commit

Permalink
useClickOutside: returning ref
Browse files Browse the repository at this point in the history
  • Loading branch information
nirnejak committed Nov 16, 2024
1 parent 2824758 commit d5e8164
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions hooks/useClickOutside.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
import * as React from "react"

const useClickOutside = (ref, handler) => {
type Event = MouseEvent | TouchEvent

const useClickOutside = (
handler: (event: Event) => void
): React.RefObject<HTMLElement> => {
const ref = React.useRef<HTMLElement>(null)

React.useEffect(() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) {
const listener = (event: Event): void => {
const el = ref?.current
if (el == null || el.contains(event?.target as Node)) {
return
}

handler(event)
handler(event) // Call the handler only if the click is outside of the element passed.
}

document.addEventListener("click", listener)
document.addEventListener("mousedown", listener)
document.addEventListener("touchstart", listener)

return () => {
document.removeEventListener("click", listener)
document.removeEventListener("mousedown", listener)
document.removeEventListener("touchstart", listener)
}
}, [ref, handler])
}, [ref, handler]) // Reload only if ref or handler changes

return ref
}

export default useClickOutside

0 comments on commit d5e8164

Please sign in to comment.