forked from vercel/commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclick-outside.tsx
42 lines (35 loc) · 938 Bytes
/
click-outside.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
33
34
35
36
37
38
39
40
41
42
import React, { useRef, useEffect, MouseEvent } from 'react'
import hasParent from './has-parent'
interface ClickOutsideProps {
active: boolean
onClick: (e?: MouseEvent) => void
children: any
}
const ClickOutside = ({
active = true,
onClick,
children,
}: ClickOutsideProps) => {
const innerRef = useRef()
const handleClick = (event: any) => {
if (!hasParent(event.target, innerRef?.current)) {
if (typeof onClick === 'function') {
onClick(event)
}
}
}
useEffect(() => {
if (active) {
document.addEventListener('mousedown', handleClick)
document.addEventListener('touchstart', handleClick)
}
return () => {
if (active) {
document.removeEventListener('mousedown', handleClick)
document.removeEventListener('touchstart', handleClick)
}
}
})
return React.cloneElement(children, { ref: innerRef })
}
export default ClickOutside