@utilityjs/use-event-listener
v1.0.6
Published
A React hook that handles binding/unbinding event listeners in a smart way.
Downloads
773
Maintainers
Readme
A React hook that handles binding/unbinding event listeners in a smart way.
npm i @utilityjs/use-event-listener | yarn add @utilityjs/use-event-listener
Usage
useEventListener({
target: document,
eventType: "click",
handler: event => console.log(event)
});
useEventListener({
target: window,
eventType: "click",
handler: event => console.log(event)
});
useEventListener({
target: document.getElementById("target"),
eventType: "click",
handler: event => console.log(event)
});
API
useEventListener(config, shouldAttach?)
type UseEventListener = {
<K extends keyof DocumentEventMap, T extends Document = Document>(
config: {
target: T | null;
eventType: K;
handler: DocumentEventListener<K>;
options?: Options;
},
shouldAttach?: boolean
): void;
<K extends keyof WindowEventMap, T extends Window = Window>(
config: {
target: T | null;
eventType: K;
handler: WindowEventListener<K>;
options?: Options;
},
shouldAttach?: boolean
): void;
<K extends keyof HTMLElementEventMap, T extends HTMLElement = HTMLElement>(
config: {
target: React.RefObject<T> | T | null;
eventType: K;
handler: ElementEventListener<K>;
options?: Options;
},
shouldAttach?: boolean
): void;
};
declare const useEventListener: UseEventListener;
config
config.target
The target to which the listener will be attached.
config.eventType
A case-sensitive string representing the event type to listen for.
config.handler
See The event listener callback for details on the callback itself.
config.options
See The event listener callback for details on the third parameter.
shouldAttach
If set to false
, the listener won't be attached. (default = true)