A simple React Hook for listening events of HTML element
$ yarn add use-event-handler
export default () => {
const ref = useRef<HTMLDivElement>(null);
useEvent('click', event => console.log(event), { element: ref.current });
return <div ref={ref} />;
};
useEvent(type, handler, options)
- type*: A string of event name
- handler*: A function that will be called whenever
eventName
trigger onelement
. - options: An object of
{ element?: Element, capture?: boolean, passive?: boolean, once?: boolean }
, where element is the element to add the event listener, and others will be passed toaddEvenetListener
. MDN