beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
31 lines (30 loc) • 1.18 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 = (ref, eventName, options) => {
const [handler, setHandler] = createHandlerSetter();
if (!!ref && !safeHasOwnProperty(ref, 'current')) {
throw new Error('Unable to assign any scroll event to the given ref');
}
useEffect(() => {
const cb = (event) => {
if (handler.current) {
handler.current(event);
}
};
if (ref.current && ref.current.addEventListener && handler.current) {
ref.current.addEventListener(eventName, cb, options);
}
return () => {
if (ref.current && ref.current.addEventListener && handler.current) {
ref.current.removeEventListener(eventName, cb, options);
}
};
}, [eventName, ref.current, options]);
return setHandler;
};
export default useEvent;