UNPKG

react-outclick

Version:

A React component for handling clicks outside of a component

57 lines (52 loc) 2.35 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); /** * @class OnOutsiceClick */ var OnOutsiceClick = function (props) { var container = props.container, onOutsideClick = props.onOutsideClick, _a = props.mouseEvent, mouseEvent = _a === void 0 ? "click" : _a, _b = props.touchEvent, touchEvent = _b === void 0 ? "touchend" : _b, children = props.children, _c = props.display, display = _c === void 0 ? "block" : _c; var style = React.useMemo(function () { return { display: display, }; }, [display]); var node = React.useRef(null); var checkInsideContainer = container && container.current; React.useEffect(function () { var currContainer = checkInsideContainer; var handleEvents = function (event) { // if clicked inside the component then dont respond if (node.current && node.current.contains(event.target)) { return; } // if a container is present and it is clicked inside of that then respond if (container && container.current.contains(event.target)) { return onOutsideClick(event); } // respond return onOutsideClick(event); }; if (checkInsideContainer) { currContainer.addEventListener(mouseEvent, handleEvents); currContainer.addEventListener(touchEvent, handleEvents); } else { document.addEventListener(mouseEvent, handleEvents); document.addEventListener(touchEvent, handleEvents); } return function () { if (checkInsideContainer) { currContainer.removeEventListener(mouseEvent, handleEvents); currContainer.removeEventListener(touchEvent, handleEvents); } else { document.removeEventListener(mouseEvent, handleEvents); document.removeEventListener(touchEvent, handleEvents); } }; }, [container, checkInsideContainer, mouseEvent, onOutsideClick, touchEvent]); return (React.createElement("div", { style: style, ref: node }, children)); }; exports.default = OnOutsiceClick; //# sourceMappingURL=index.js.map