useWindowEvent
Add event listener to window.
APIâ
useWindowEvent(eventType, handler);
Optionsâ
eventType: string
(Required)- The type of window event
- See https://developer.mozilla.org/en-US/docs/Web/API/Window#events
handler: (ev: WindowEventMap[T]) => any
(Required)- Handler
Returnsâ
No return
Examplesâ
http://localhost:3000/
âšī¸ Click anywhere or type anything
Last clicked coordinate: -, -
Last pressed key: ""
- JS
- TS
import { useState } from 'react';
import { useWindowEvent } from 'react-power-ups';
export function Demo() {
const [coord, setCoord] = useState<number[]>([]);
const [key, setKey] = useState('');
useWindowEvent('click', (evt) => {
setCoord([evt.clientX, evt.clientY]);
});
useWindowEvent('keyup', (evt) => {
setKey(evt.key);
});
return (
<>
<div className="pt-4">
Last clicked coordinate: {coord[0] ?? '-'}, {coord[1] ?? '-'}
</div>
<div>Last pressed key: "{key}"</div>
</>
);
}
import { useState } from 'react';
import { useWindowEvent } from 'react-power-ups';
export function Demo() {
const [coord, setCoord] = useState([]);
const [key, setKey] = useState('');
useWindowEvent('click', (evt) => {
setCoord([evt.clientX, evt.clientY]);
});
useWindowEvent('keyup', (evt) => {
setKey(evt.key);
});
return (
<>
<div className="pt-4">
Last clicked coordinate: {coord[0] ?? '-'}, {coord[1] ?? '-'}
</div>
<div>Last pressed key: "{key}"</div>
</>
);
}
Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-window-event.ts