@utilityjs/use-event-listener
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

useEventListener

A React hook that handles binding/unbinding event listeners in a smart way.

license npm latest package npm downloads types

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)

Package Sidebar

Install

npm i @utilityjs/use-event-listener

Weekly Downloads

55

Version

1.0.6

License

MIT

Unpacked Size

10.7 kB

Total Files

8

Last publish

Collaborators

  • mimshins