[go: up one dir, main page]

react-use-keypress

1.3.1 • Public • Published

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.

Package Sidebar

Install

npm i react-use-keypress

Weekly Downloads

12,753

Version

1.3.1

License

MIT

Unpacked Size

18.9 kB

Total Files

7

Last publish

Collaborators

  • jacobbuck