useEventListener
Set up the event listener to the target.
API
function useEventListener<
T extends EventTarget = EventTarget,
E extends Event = Event
>(
target: EffectTarget<T>,
eventName: string,
listener: (event: E) => void,
options?: boolean | { capture?: boolean; once?: boolean; passive?: boolean }
): void;
type Nullable<T> = T | undefined | null;
type EffectTarget<T> =
| Nullable<T>
| (() => Nullable<T>)
| { current: Nullable<T> };
Params:
target
: Event target. It can beundefined
,null
, event target, a ref object or a function that returns a event target.eventName
: Event name.listener
: Listener function.options
: Similar to the third parameter of theaddEventListener
function.
Example
import React, { useRef } from "react";
import { useEventListener } from "@lilib/hooks";
function Example() {
const buttonRef = useRef<HTMLButtonElement>(null);
useEventListener(buttonRef, "click", () => {
alert("Click");
});
return <button ref={buttonRef}>Click</button>;
}
export default Example;