forked from M-Labs/web2019
31 lines
771 B
JavaScript
31 lines
771 B
JavaScript
|
import React from "react";
|
||
|
|
||
|
// copy from "@uidotdev/usehooks"
|
||
|
|
||
|
export function useClickAway(cb) {
|
||
|
const ref = React.useRef(null);
|
||
|
const refCb = React.useRef(cb);
|
||
|
|
||
|
React.useLayoutEffect(() => {
|
||
|
refCb.current = cb;
|
||
|
});
|
||
|
|
||
|
React.useEffect(() => {
|
||
|
const handler = (e) => {
|
||
|
const element = ref.current;
|
||
|
if (element && !element.contains(e.target)) {
|
||
|
refCb.current(e);
|
||
|
}
|
||
|
};
|
||
|
|
||
|
document.addEventListener("mousedown", handler);
|
||
|
document.addEventListener("touchstart", handler);
|
||
|
|
||
|
return () => {
|
||
|
document.removeEventListener("mousedown", handler);
|
||
|
document.removeEventListener("touchstart", handler);
|
||
|
};
|
||
|
}, []);
|
||
|
|
||
|
return ref;
|
||
|
}
|