UNPKG

pouncejs

Version:

A collection of UI components from Panther labs

36 lines (32 loc) 1.03 kB
import React from 'react'; var useOutsideClick = function useOutsideClick(_ref) { var refs = _ref.refs, callback = _ref.callback, _ref$disabled = _ref.disabled, disabled = _ref$disabled === void 0 ? false : _ref$disabled; // Invoke a callback on clicks outside of those elements. We also add `capture` events to avoid // some race conditions on window-attached events var listener = React.useCallback(function (event) { var isOutsideClick = refs.every(function (ref) { return ref.current && !ref.current.contains(event.target); }); if (isOutsideClick) { callback(event); } }, [callback].concat(refs)); React.useEffect(function () { if (!disabled) { window.addEventListener('mousedown', listener, { capture: true }); } return function () { if (!disabled) { window.removeEventListener('mousedown', listener, { capture: true }); } }; }, [listener, disabled]); }; export default useOutsideClick;