-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.js
More file actions
23 lines (23 loc) · 810 Bytes
/
hook.js
File metadata and controls
23 lines (23 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useEffect } from 'react';
function useClickAwayListener(element, onClickAway, exclude = []) {
useEffect(() => {
if (!element)
return;
const listener = (event) => {
if (!(event.target instanceof Node)) {
return;
}
const node = event.target;
if ((element && element.contains(node)) ||
exclude.some((item) => item instanceof Element && item.contains(node))) {
return;
}
onClickAway && onClickAway(event);
};
document.addEventListener('mouseup', listener);
return () => {
document.removeEventListener('mouseup', listener);
};
}, [element, onClickAway, ...exclude]);
}
export default useClickAwayListener;