beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
33 lines (32 loc) • 1.31 kB
JavaScript
import { useEffect } from 'react';
import createHandlerSetter from './factory/createHandlerSetter';
import safeHasOwnProperty from './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.
*/
const useEvent = (target, eventName, options) => {
const [handler, setHandler] = createHandlerSetter();
if (!!target && !safeHasOwnProperty(target, 'current')) {
throw new Error('Unable to assign any scroll event to the given ref');
}
useEffect(() => {
var _a;
const cb = (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 () => {
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;
};
export default useEvent;