useEventListener
Use addEventListener elegant by Hook.
Overview
Use addEventListener elegant by Hook.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useEventListener.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useEventListener.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useEventListener.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useEventListener.jsonUse addEventListener elegant by Hook.
Examples
Default usage
Listen for keydown
Listen for multiple events
API
useEventListener(
eventName: string,
handler: (ev: Event) => void,
options?: Options,
);Property
| Property | Description | type | default |
| - | -- | ----- |
| target | DOM element or ref | (() => Element) | Element | React.MutableRefObject<Element> | Window | Document | window |
| capture | Optional, a Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. | boolean | false |
| once | Optional, A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. | boolean | false |
| passive | Optional, A Boolean which, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. | boolean | false |
| enable | Optional, Whether to enable listening. | boolean | true |
useEventEmitter
Sometimes it is difficult to pass events between multiple components. By using EventEmitter, this can be simplified.
useEventTarget
A hook that encapsulates onChange and value logic for form controls that obtains value through event.target.value. It also supports custom transformer and reset functionalities.