Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-use-keypress

jacobbuck58.7kMIT1.3.1

React hook which listens for pressed keys

event, hook, key, keyboard, keydown, keypress, react, window

readme

react-use-keypress

React hook which listens for pressed keys.

Usage

useKeypress(keys, handler);

Parameters

  • 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.

Example

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();
    }
  });
  // ...
};

Browser Support

Includes a shim for the KeyboardEvent.key property to handle inconsistencies from Internet Explorer and older versions of Edge and Firefox.

Requirements

Requires a minimum of React version 16.8.0 for the Hooks API.

changelog

Changelog

v1.3.1 - 2022-04-14

Changed

v1.3.0 - 2021-05-02

Added

Changed

  • Changed type checking to use invariant function from tiny-invariant.

Removed

v1.2.0 - 2020-11-21

Added

  • Added source maps to build output.

Changed

v1.1.0 - 2020-10-25

Added

  • Added type checking of parameters in useKeypress hook.

Changed

v1.0.1 - 2020-07-09

Added

v1.0.0 - 2020-05-19

Initial public version! :tada: