useEventListener
Use EventListener with ease.
Usage
Live Editor
function Demo() { const buttonRef = useRef<HTMLButtonElement>(null); const [state, setState] = useState("NO DB Click"); const onDBClick = () => { setState("DB Clicked"); }; const onClick = (event: Event) => { console.log("button clicked!", event); }; const onVisibilityChange = (event: Event) => { console.log("doc visibility changed!", { isVisible: !document.hidden, event, }); }; // example with window based event useEventListener("dblclick", onDBClick); // example with document based event useEventListener("visibilitychange", onVisibilityChange, () => document); // example with element based event useEventListener("click", onClick, buttonRef); return ( <div> <p>{state}</p> <button ref={buttonRef}>Click me</button> </div> ); };
Result
Loading...
API
useEventListener
Returns
void
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
eventName | event name | string (Required) | - |
handler | event handler | (event: any) => void (Required) | - |
element | dom element | EventTarget | Element | Document | HTMLElement | Window | null | undefined | window |
options | listener options | boolean | AddEventListenerOptions | undefined | - |