1.1.0 • Published 4 years ago

react-use-key v1.1.0

Weekly downloads
34
License
MIT
Repository
github
Last release
4 years ago

react-use-key

React hook for key binding and execute handler

NPM JavaScript Style Guide

Install

npm install --save react-use-key

or

yarn add react-use-key

Usage

import React from 'react'

import useKey from 'react-use-key'

function Example(props) {
  const changeDocument = (e) => {
    let newText = `You pressed '${e.key}' `
    if (e.ctrlKey) newText += 'with CTRL, '
    if (e.altKey) newText += 'with ALT, '
    if (e.shiftKey) newText += 'with SHIFT, '
    if (e.metaKey) newText += 'with Meta, '
    setText(newText)
  }

  //Simple use
  useKey('a', changeDocument, null)

  //More than 1 match expression:
  useKey('a|1|4|j|g', changeDocument, null)

  //Combinations
  useKey('ctrl+shift+1', changeDocument, null)

  //Complex combinations
  useKey('ctrl+shift+f | p', changeDocument, null)
  useKey('alt+KeyG', changeDocument, { matchStrategy: 'code' })
  useKey('meta+d', changeDocument, { preventDefault: true })

  return <></>
}

Additional Options

The third parameter is an optional configuration object that includes:

KeyDescriptionDefault
separatorSeparator character for combinations patterns+
orSeparatorCharacter that separates patterns when more than one is available|
matchStrategyThe key from the javascript event object that will be used to match the passed key. The availables options are key and code. When code is selected you will have to pass the complete code of the character. e.g Numpad1 will only match if the pressed key is 1 from the Numpadkey
preventDefaultIf the event should prevent the default key behaviourfalse
eventTypeJavascript native event type. Options are: keypress, keydown, keyupkeydown

Thanks for downloading

Feel free to report an issue or to create new features

License

MIT © wmattei

1.1.0

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago