0.1.1 • Published 6 years ago

link-to-key v0.1.1

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

link-to-key

Build Status codecov

Simply link an action to a keypress.

Contents

Installation

To install using npm:

npm install -P link-to-key

or using yarn:

yarn add link-to-key

Usage

I use the library primarily with react and to add a keyboard handler for accessibility:

// Create a clickable react component:
const Component = ({ onClick }) => (
  <div
    role="button"
    onClick={onClick}
  >
    Click me!
  </div>
);

Refactor it, to have better accessibility:

import linkToKey from 'link-to-key';

// Make component focusable and call onClick when ENTER is pressed.
const Component = ({ onClick }) => {
  const onKeyPress = linkToKey('Enter', onClick);
  return (
    <div
      role="button"
      tabIndex="0"
      onClick={onClick}
      onKeyPress={onKeyPress}
    >
      Click me!
    </div>
  );
};

Documentation

The library exports a single function as default. To use it just:

import linkToKey from 'link-to-key';

linkToKey

const onKeyPress = linkToKey(key, action);
ParametertypeDescription
keystringorArray<string>The key that should trigger the action. It must be the same string that gets passed as key property of KeyboardEvent.If an array is passed, the action trigger on any of these keys.
actionFunctionThe action that should be triggered.
ReturnsFunctionA function, that needs to be called with the event to check the key and trigger the action if appropriate. All excess parameters are passed to action.

License and Copyright

MIT © Marc Reuter