React hook that listens for specific key presses.
npm install react-use-keypressReact hook that listens for specific key presses.
``jsx`
useKeypress(keys, handler);
- keys – a single key or array of key values to listen for.handler
- – function called when a matching key is pressed.
Single key:
`jsx
import useKeypress from "react-use-keypress";
const Example = (props) => {
// ...
useKeypress("Escape", () => {
// Do something when the user has pressed the Escape key
});
// ...
};
`
Multiple keys:
`jsx
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 in older browsers.
Requires React 16.8.0 or higher (Hooks API).