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
- the specified event(s).
- the event(s) handler.
- the addEventListener options, as well as the
target
object that can be an element or a ref object element that hasaddEventListener
method.
WARNING
You must always specify a target
object otherwise it will not work.
Example Usage
- 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>;
}
- 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>;
}