2.2.2 • Published 4 years ago

use-keyboard-shortcuts v2.2.2

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

use-keyboard-shortcuts

An intuitive React hook to enable keyboard shortcuts.

NPM JavaScript Style Guide

Quick Example

  useKeyboardShortcuts([
    { keys: ["ctrl", "a"], onEvent: event => alert("ctrl + a was pressed") },
    { keys: ["shift", "b"], onEvent: event => alert("shift + b was pressed") },
    { keys: ["Tab"], handleNext },
    { keys: ["Esc"], handleClose },
    { keys: ["Enter"], handleSubmit },
  ])

  useKeyboardShortcuts(
    [{ keys: ["ctrl", "shift"], onEvent: () => alert('ctrl + shift + scroll is active') }],
    true,
    [],
    "mousewheel"
  )
}

Features

  • Easy to use
  • Typescript support
  • Multiple shortcuts registered at the same time
  • Support for special keys: Shift, Ctrl (command on Mac), Alt (option on Mac).
  • Support for keydown and mousewheel events
  • Prevents mature propagation. This means that if you have a shortcut for ctrl + a and ctrl + shift + a in the same hook, then the action for ctrl + a will not trigger when pressing ctrl + shift + a.

Install

$ npm install --save use-keyboard-shortcuts
$ yarn add use-keyboard-shortcuts

Usage

import React from "react"
import useKeyboardShortcuts from "use-keyboard-shortcuts"

const Example = () => {
  const [isOpen, setIsOpen] = React.useState(false)

  useKeyboardShortcuts([
    { keys: ["ctrl", "a"], onEvent: event => alert("ctrl + a was pressed") },
    { keys: ["Esc"], onEvent: () => setIsOpen(false)  },
  ])

  return <div>...</div>
}

Arguments

Argument (in order)TypeDefaultDescription
shortcutsShortcut[]undefinedArray of Shortcut-objects that should listen to the specified dependencies and eventType. See Shortcut object-section.
activebooleantrueDisables or enables all shortcuts.
dependenciesany[][]List dependencies of the shortcuts
eventType"keydown"/"mousewheel""keydown"Wether it should listen for keyboard or mouse scroll events

Shortcut object

KeyTypeDescription
keysstring[]Combination of keys that needs to be pressed to trigger onEvent().
onEventfunction(event)Action for when combination in keys are pressed.
disabledbooleanUsed to disable a shortcut in particular

Example

See the example-folder for an extended example of how to use this hook with the mousewheel event type.

License

MIT � SAITS

2.2.2

4 years ago

2.2.1

4 years ago

2.2.0

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago