React hook which listens for pressed keys.
useKeypress(keys, handler);
keys
a single or array of key value(s) to listen to.handler
function to be called when one of the matching key values has been pressed.
Listening to a single key:
import useKeypress from 'react-use-keypress';
const Example = (props) => {
// ...
useKeypress('Escape', () => {
// Do something when the user has pressed the Escape key
});
// ...
};
Listening to multiple keys:
import useKeypress from 'react-use-keypress';
const Example = (props) => {
// ...
useKeypress(['ArrowLeft', 'ArrowRight'], (event) => {
if (event.key === 'ArrowLeft') {
moveLeft();
} else {
moveRight();
}
});
// ...
};
Includes a shim for the KeyboardEvent.key
property to handle inconsistencies from Internet Explorer and older versions of Edge and Firefox.
Requires a minimum of React version 16.8.0 for the Hooks API.