Skip to main content

useWindowEvent

Add event listener to window.


API​

useWindowEvent(eventType, handler);

Options​

Returns​

No return


Examples​

http://localhost:3000/
ℹī¸ Click anywhere or type anything
Last clicked coordinate: -, -
Last pressed key: ""
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: &quot;{key}&quot;</div>
</>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-window-event.ts