web2019/static/js/shop/options/useClickAway.js
Egor Savkin da3f18d6d9 Slightly reduce dependencies
Signed-off-by: Egor Savkin <es@m-labs.hk>
2024-01-09 10:14:53 +08:00

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;
}