UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

38 lines (37 loc) 1.65 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var createHandlerSetter_1 = __importDefault(require("./factory/createHandlerSetter")); var safeHasOwnProperty_1 = __importDefault(require("./shared/safeHasOwnProperty")); /** * Accepts the reference to an HTML Element and an event name then performs the necessary operations to listen to the event * when fired from that HTML Element. */ var useEvent = function (target, eventName, options) { var _a = (0, createHandlerSetter_1.default)(), handler = _a[0], setHandler = _a[1]; if (!!target && !(0, safeHasOwnProperty_1.default)(target, 'current')) { throw new Error('Unable to assign any scroll event to the given ref'); } (0, react_1.useEffect)(function () { var _a; var cb = function (event) { if (handler.current) { handler.current(event); } }; if (((_a = target.current) === null || _a === void 0 ? void 0 : _a.addEventListener) && handler.current) { target.current.addEventListener(eventName, cb, options); } return function () { var _a; if (((_a = target.current) === null || _a === void 0 ? void 0 : _a.addEventListener) && handler.current) { target.current.removeEventListener(eventName, cb, options); } }; }, [eventName, target.current, options]); return setHandler; }; exports.default = useEvent;