Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/hooks/useOutsideClick.js
6408 views
1
import { useRef, useEffect } from "react";
2
3
const useOutsideClick = (callback, exceptionDomIds) => {
4
const ref = useRef();
5
6
const isOutsideOfException = (target) => {
7
if (exceptionDomIds && exceptionDomIds.length > 0) {
8
return !exceptionDomIds.some((id) => {
9
const element = document.getElementById(id);
10
return element && element.contains(target);
11
});
12
}
13
14
return true;
15
};
16
17
const isOutsideOfElement = (target) => ref.current && !ref.current.contains(target);
18
19
const handleClick = ({ target }) => {
20
if (isOutsideOfElement(target) && isOutsideOfException(target)) {
21
callback();
22
}
23
};
24
25
useEffect(() => {
26
if (window !== undefined) {
27
document.addEventListener("click", handleClick);
28
}
29
return () => {
30
if (window !== undefined) {
31
document.removeEventListener("click", handleClick);
32
}
33
};
34
// eslint-disable-next-line react-hooks/exhaustive-deps
35
}, []);
36
37
return ref;
38
};
39
40
export { useOutsideClick };
41
42