useEventListenerOnRef
Adds an event listener to a element through the ref object
The useEventListenerOnRef
hook is helpful when you want attach event listener to elements through their ref objects created from React.useRef
.
The event listener attached will automatically be cleanuped once the component is unmounted.
useEventListenerOnRef
Click on the button to trigger the event
Usage
Import the hook from @abhushanaj/react-hooks
and use in required component.
Properties
- When using the
useEventListenerOnRef
hook, you don’t need to memoize the callback withReact.useCallback
or similar. As the callback is not utilized as a dependency in theuseEffect
, the listener does not remove and attach itself again on change of the callback callback functions’ reference identity.
- You can pass any options defined on
AddEventListenerOptions
to the event handler as defined on MDN spec.
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
ref | TargetRef | The target ref on which you want to attach the listeners. | N/A |
eventName | string | The name of the event to listen to. | N/A |
callback | EventListenerOrEventListenerObject | The event handler function to be executed when the event is triggered. | N/A |
options | AddEventListenerOptions | boolean (optional) | Additional options for the event listener. | undefined |
Note: The EventListenerOrEventListenerObject
and AddEventListenerOptions
are standard types defined by lib.dom.d.ts
. You can refer the MDN spec for additional information.