-
Notifications
You must be signed in to change notification settings - Fork 0
/
useClickOutsideElement.ts
61 lines (60 loc) · 1.47 KB
/
useClickOutsideElement.ts
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import * as React from 'react'
/**
* This function is a react hook for watching for click events outside of a
* particular element. The hook will add and remove its own `eventListener`.
*
* - For performance reasons, it is important to pass a memoised function as the
* callback argument, eg:
*
* ```js
* React.useCallback(() => {}, [])
* ```
*
* ## Example
*
* ```js
* import * as React from 'react'
* import { useClickOutsideElement } from '@oneblink/apps-react'
*
* const MyComponent = () => {
* const narrowDivRef = React.useRef(null)
* useClickOutsideElement(
* narrowDivRef,
* React.useCallback(() => {
* console.log('Wide Div was clicked outside of narrow div...')
* }, []),
* )
*
* return (
* <div className="wide-div">
* <div ref={narrowDivRef} className="narrow-div"></div>
* </div>
* )
* }
*
* export default MyComponent
* ```
*
* @param ref
* @param callback
* @group Hooks
*/
export default function useClickOutsideElement(
ref: { current: HTMLElement | null },
callback: () => void,
) {
const handleClickOutside = React.useCallback(
(event: Event) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback()
}
},
[callback, ref],
)
React.useEffect(() => {
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [handleClickOutside])
}