Home

Awesome

react-key-handler 🔑

npm version License Build Status

React component to handle keyboard events (such as keyup, keydown & keypress).

Testimonials

<div>“Happy to see that react-key-handler is SSR safe :+1:”</div> [Veselin Todorov](https://github.com/vesln), Chai.js core

Table of Contents

  1. Installation
  2. Usage
    1. Higher-order Components
    2. Component
    3. Form key handling
  3. Key event names
  4. keyValue, code and keyCode
  5. Development
    1. Setup
    2. Getting started
    3. Tests
  6. Contributing
  7. License

Installation

$ npm install react-key-handler --save

Usage

You can use react-key-handler library in two flavours:

Higher-order Components

This library includes two similar higher-order components, but with a different puprose:

Higher-order ComponentPurpose
keyHandlerHandles key changes
keyToggleHandlerHandles key toggles

Both have the same API and will decorate the given component with a keyValue, code and keyCode property.

Internally the KeyHandler component is used, for a full understanding be sure to check out the implementation.

import React from 'react';
import { keyHandler, KEYPRESS } from 'react-key-handler';

function Demo({ keyValue }) {
  return (
    <div>
      {keyValue === 's' && (
        <ol>
          <li>hello</li>
          <li>world</li>
        </ol>
      )}
    </div>
  );
}

export default keyHandler({ keyEventName: KEYPRESS, keyValue: 's' })(Demo);

The prop types of the KeyHandler component are:

NameTypeRequiredDefault
keyEventNamestringno'keyup''keydown', 'keypress' or 'keyup'
keyValuestringyes *Any given KeyboardEvent.key
codestringyes *Any given KeyboardEvent.code
keyCode†numberyes *Any given KeyboardEvent.keyCode

* You should pass at least one of these props.

† Note that the keyCode is frequently browser specific and has therefore be set as deprecated, see MDN for details.

Examples

Component

import React from 'react';
import KeyHandler, { KEYPRESS } from 'react-key-handler';

export default class Demo extends React.Component {
  state = { showMenu: false };

  render() {
    const { showMenu } = this.state;

    return (
      <React.Fragment>
        <KeyHandler
          keyEventName={KEYPRESS}
          keyValue="s"
          onKeyHandle={this.toggleMenu}
        />

        {showMenu && (
          <ol>
            <li>hello</li>
            <li>world</li>
          </ol>
        )}
      </React.Fragment>
    );
  },

  toggleMenu = (event) => {
    event.preventDefault();

    this.setState({ showMenu: !this.state.showMenu });
  };
}

The prop types of the KeyHandler component are:

NameTypeRequiredDefault
keyEventNamestringno'keyup''keydown', 'keypress' or 'keyup'
keyValuestringyes *Any given KeyboardEvent.key
codestringyes *Any given KeyboardEvent.code
keyCode†numberyes *Any given KeyboardEvent.keyCode
onKeyHandlefunctionyesFunction that is called when they key is handled

* You should pass at least one of these props.

† Note that the keyCode is frequently browser specific and has therefore be set as deprecated, see MDN for details.

Example

Form key handling

This library does not handle key events for form elements such as <input /> and <textarea />.

React does a fine job supporting these already via keyboard events.

Examples

Key event names

TODO: explain the differences between the different key events.

keyValue, code and keyCode

The three available key events are

We recommend you to use the new Web standard KeyboardEvent.key or the KeyboardEvent.code over the deprecated KeyboardEvent.keyCode.

Note that in React key is a reserved property, and thus we use keyValue when referring to the key property.

Browser support:

There's no need to worry about browser support because internally we normalize deprecated HTML5 keyValue values and translate from legacy keyCode values, similar to how React does this for their SyntheticKeyboardEvent.

More information:

W3C Working Draft.

Development

Setup

$ git clone <this repo>
$ cd react-key-handler
$ npm install

Getting started

To start the server:

$ npm demo

This starts a development server, which will automatically rebuild the demo app as you change files and supports hot module replacement for fast development:

$ open http://localhost:1234

Tests

To run all tests:

$ npm test

Or you can run the linters, unit tests and check for type errors individually:

$ npm run test:lint
$ npm run test:unit
$ npm run test:flow

Contributing

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

 _________________
< The MIT License >
 -----------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||