generated from nirnejak/nextjs-typescript-saas
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseClickOutside.tsx
32 lines (24 loc) · 876 Bytes
/
useClickOutside.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import * as React from "react"
type Event = MouseEvent | TouchEvent
const useClickOutside = (
handler: (event: Event) => void
): React.RefObject<HTMLDivElement | null> => {
const ref = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
const listener = (event: Event): void => {
const el = ref?.current
if (el == null || el.contains(event?.target as Node)) {
return
}
handler(event) // Call the handler only if the click is outside of the element passed.
}
document.addEventListener("mousedown", listener)
document.addEventListener("touchstart", listener)
return () => {
document.removeEventListener("mousedown", listener)
document.removeEventListener("touchstart", listener)
}
}, [ref, handler]) // Reload only if ref or handler changes
return ref
}
export default useClickOutside