@gravity-ui/uikit
Version:
Gravity UI base styling and components
32 lines (31 loc) • 1.13 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useOutsideClick = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
/**
* Hook for observing clicks outside a given target
*
* @param ref - purpose of observation
* @param handler - callback when a click is triggered outside the observation target
*
* @return - nothing
*/
const useOutsideClick = ({ ref, handler }) => {
React.useEffect(() => {
const callback = (e) => {
const elem = ref?.current;
if (elem && !elem.contains(e.target) && handler) {
handler(e);
}
};
window.addEventListener('mouseup', callback, { capture: true });
window.addEventListener('touchend', callback, { capture: true });
return () => {
window.removeEventListener('mouseup', callback, { capture: true });
window.removeEventListener('touchend', callback, { capture: true });
};
}, [handler, ref]);
};
exports.useOutsideClick = useOutsideClick;
//# sourceMappingURL=useOutsideClick.js.map
;