Skip to content

useEventListener

Add one or multiple event listeners to a specific target element, window, or document object, if you're using typescript you will get auto-completion for the event listeners.

Parameters

  1. the specified event(s).
  2. the event(s) handler.
  3. the addEventListener options, as well as the target object that can be an element or a ref object element that has addEventListener method.

WARNING

You must always specify a target object otherwise it will not work.

Example Usage

  1. Using a single event:
tsx
import { useEventListener } from 'react-pre-hooks';

export default function Example() {
  useEventListener(
    'resize',
    event => {
      console.log('width', window.innerWidth, ', height', window.innerHeight);
    },
    { target: window }
  );

  return <main></main>;
}
import { useEventListener } from 'react-pre-hooks';

export default function Example() {
  useEventListener(
    'resize',
    event => {
      console.log('width', window.innerWidth, ', height', window.innerHeight);
    },
    { target: window }
  );

  return <main></main>;
}
  1. Using a multiple events:
tsx
import { useRef } from 'react';
import { useEventListener } from 'react-pre-hooks';

export default function Example() {
  const ref = useRef<HTMLDivElement>(null);

  useEventListener(
    ['click', 'mousemove'],
    event => {
      console.log({ x: event.offsetX, y: event.offsetY });
    },
    { target: ref }
  );

  return <div ref={ref}>Click or move your cursor..</div>;
}
import { useRef } from 'react';
import { useEventListener } from 'react-pre-hooks';

export default function Example() {
  const ref = useRef<HTMLDivElement>(null);

  useEventListener(
    ['click', 'mousemove'],
    event => {
      console.log({ x: event.offsetX, y: event.offsetY });
    },
    { target: ref }
  );

  return <div ref={ref}>Click or move your cursor..</div>;
}

Released under the MIT License.