react-use-keypress

React hook which listens for pressed keys.

Usage no npm install needed!

<script type="module">
  import reactUseKeypress from 'https://cdn.skypack.dev/react-use-keypress';
</script>

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.