useEventListener
Add event listeners to a target item or document.
Features
- Automatically removes the event listener when the component unmounts.
- Supports a ref object as a target element.
- You can specify event options such as
capture,once, andpassive. - Full TypeScript support for event type.
Installation
Install the custom hook from your command line.
npm i @raddix/use-event-listener
Usage
Add an event to the window object
In this example, the handle function will be called when the click event is triggered on the window object.
By default, the event listener will be added to the global window object. Therefore, it is not necessary to specify the target object.
Add an event to a element
In this example, the handle function will be called when the mousemove event
is triggered on the div element.
To add an event listener to a element, you need to pass its ref to the target option.
API
Parameters
| Parameter | Description | Required | Type |
|---|---|---|---|
| type | The event type to listen for. It can be any event type supported by the browser. | Yes | string |
| handler | The function that is called when the event is triggered. | Yes | function |
| options | The options object. | No | object |
Configurable options
| Option | Description | Required | Type |
|---|---|---|---|
| target | The target element to add the event listener to. It can be a ref object or a DOM element. | No | RefObject | HTMLElement |
| capture | 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. | No | boolean |
| once | 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. | No | boolean |
| passive | A Boolean indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning. | No | boolean |