react-shortcuts vs react-hotkeys
Keyboard Shortcut Libraries for React
react-shortcutsreact-hotkeysSimilar Packages:

Keyboard Shortcut Libraries for React

Keyboard shortcut libraries for React facilitate the implementation of keyboard shortcuts in web applications, enhancing user experience by allowing quick access to functionalities without relying solely on mouse interactions. These libraries provide a structured way to define, manage, and respond to keyboard events, making it easier for developers to create intuitive interfaces that can be navigated efficiently. They help in improving accessibility and can significantly boost productivity for users who prefer keyboard navigation over mouse clicks.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-shortcuts19,88532830.1 kB52-MIT
react-hotkeys02,165-1087 years agoISC

Feature Comparison: react-shortcuts vs react-hotkeys

Complexity of Key Bindings

  • react-shortcuts:

    react-shortcuts is designed for simpler key bindings, focusing on ease of use rather than complexity. It allows for basic key shortcuts but may not handle intricate combinations as effectively as react-hotkeys.

  • react-hotkeys:

    react-hotkeys supports complex key combinations, including modifiers like Ctrl, Shift, and Alt, allowing developers to create intricate shortcuts that can enhance user interaction significantly. It provides a robust API for defining these combinations in a clear and manageable way.

Customization

  • react-shortcuts:

    react-shortcuts provides limited customization compared to react-hotkeys. It is more suited for straightforward applications where predefined shortcuts are sufficient, making it less flexible for complex scenarios.

  • react-hotkeys:

    react-hotkeys offers extensive customization options, enabling developers to define their own key mappings and handle conflicts between shortcuts. This flexibility is crucial for applications that require a tailored user experience and need to accommodate various user preferences.

Performance

  • react-shortcuts:

    react-shortcuts is lightweight and performs well for basic use cases. However, it may not be as optimized for performance in scenarios involving many shortcuts or complex interactions, as it lacks some of the advanced features found in react-hotkeys.

  • react-hotkeys:

    react-hotkeys is optimized for performance, ensuring that key event listeners are managed efficiently, which is essential for applications with numerous shortcuts. It minimizes the overhead associated with handling multiple key events, maintaining smooth performance even under heavy usage.

Learning Curve

  • react-shortcuts:

    react-shortcuts is easier to learn and implement, making it suitable for developers who need to quickly add basic keyboard shortcuts without delving into complex configurations.

  • react-hotkeys:

    react-hotkeys has a steeper learning curve due to its comprehensive API and the need to understand how to manage complex key combinations effectively. Developers may need to invest more time in learning the library to fully leverage its capabilities.

Community and Support

  • react-shortcuts:

    react-shortcuts has a smaller community and may have less documentation available. While it is simpler to use, developers might find fewer resources when looking for help or examples.

  • react-hotkeys:

    react-hotkeys has a larger community and more extensive documentation, providing better support and resources for developers. This can be beneficial for troubleshooting and finding examples of advanced usage.

How to Choose: react-shortcuts vs react-hotkeys

  • react-shortcuts:

    Choose react-shortcuts if you are looking for a lightweight and straightforward solution for implementing basic keyboard shortcuts. It is easier to set up and use for simpler applications where only a few keyboard shortcuts are needed, making it ideal for projects that prioritize simplicity and quick integration.

  • react-hotkeys:

    Choose react-hotkeys if you need a comprehensive solution that supports complex key combinations and offers a higher level of customization. It provides a declarative API for defining shortcuts and is suitable for applications that require extensive keyboard interactions, such as text editors or complex forms.

README for react-shortcuts

React Shortcuts

Manage keyboard shortcuts from one place.

Build Status

Intro

Managing keyboard shortcuts can sometimes get messy. Or always, if not implemented the right way.

Real problems:

  • You can't easily tell which shortcut is bound to which component
  • You have to write a lot of boilerplate code (addEventListeners, removeEventListeners, ...)
  • Memory leaks are a real problem if components don’t remove their listeners properly
  • Platform specific shortcuts is another headache
  • It's more difficult to implement feature like user-defined shortcuts
  • You can't easily get allthe application shortcuts and display it (e.g. in settings)

React shortcuts to the rescue!

With react-shortcuts you can declaratively manage shortcuts for each one of your React components.

Important parts of React Shortcuts:

  • Your keymap definition
  • ShortcutManager which handles keymap
  • <Shortcut> component for handling shortcuts

Try online demo

Edit l40jjo48nl

Quick tour

1. npm install react-shortcuts

2. Define application shortcuts

Create a new JS, Coffee, JSON or CSON file wherever you want (which probably is your project root). And define the shortcuts for your React component.

Keymap definition

{
 "Namespace": {
   "Action": "Shortcut",
   "Action_2": ["Shortcut", "Shortcut"],
   "Action_3": {
     "osx": "Shortcut",
     "windows": ["Shortcut", "Shortcut"],
     "linux": "Shortcut",
     "other": "Shortcut"
   }
 }
}
  • Namespace should ideally be the component’s displayName.
  • Action describes what will be happening. For example MODAL_CLOSE.
  • Keyboard shortcut can be a string, array of strings or an object which specifies platform differences (Windows, OSX, Linux, other). The shortcut may be composed of single keys (a, 6,…), combinations (command+shift+k) or sequences (up up down down left right left right B A).

Combokeys is used under the hood for handling the shortcuts. Read more about how you can specify keys.

Example keymap definition:
export default {
  TODO_ITEM: {
    MOVE_LEFT: 'left',
    MOVE_RIGHT: 'right',
    MOVE_UP: ['up', 'w'],
    DELETE: {
      osx: ['command+backspace', 'k'],
      windows: 'delete',
      linux: 'delete',
    },
  },
}

Save this file as keymap.[js|coffee|json|cson] and require it into your main file.

import keymap from './keymap'

3. Rise of the ShortcutsManager

Define your keymap in whichever supported format but in the end it must be an object. ShortcutsManager can’t parse JSON and will certainly not be happy about the situation.

import keymap from './keymap'
import { ShortcutManager } from 'react-shortcuts'

const shortcutManager = new ShortcutManager(keymap)

// Or like this

const shortcutManager = new ShortcutManager()
shortcutManager.setKeymap(keymap)

4. Include shortcutManager into getChildContext of some parent component. So that <shortcuts> can receive it.

class App extends React.Component {
  getChildContext() {
    return { shortcuts: shortcutManager }
  }
}

App.childContextTypes = {
  shortcuts: PropTypes.object.isRequired
}

5. Require the component

You need to require the component in the file you want to use shortcuts in. For example <TodoItem>.

import { Shortcuts } from `react-shortcuts`

class TodoItem extends React.Component {
  _handleShortcuts = (action, event) => {
    switch (action) {
      case 'MOVE_LEFT':
        console.log('moving left')
        break
      case 'MOVE_RIGHT':
        console.log('moving right')
        break
      case 'MOVE_UP':
        console.log('moving up')
        break
      case 'COPY':
        console.log('copying stuff')
        break
    }
  }

  render() {
    return (
      <Shortcuts
        name='TODO_ITEM'
        handler={this._handleShortcuts}
      >
        <div>Make something amazing today</div>
      </Shortcuts>
    )
  }
}

The <Shortcuts> component creates a <shortcuts> element in HTML, binds listeners and adds tabIndex to the element so that it’s focusable. _handleShortcuts is invoked when some of the defined shortcuts fire.

Custom props for <Shortcuts> component

  • handler: func
    • callback function that will fire when a shortcut occurs
  • name: string
    • The name of the namespace specified in keymap file
  • tabIndex: number
    • Default is -1
  • className: string
  • eventType: string
    • Just for gourmets (keyup, keydown, keypress)
  • stopPropagation: bool
  • preventDefault: bool
  • targetNodeSelector: DOM Node Selector like body or .my-class
    • Use this one with caution. It binds listeners to the provided string instead of the component.
  • global: bool
    • Use this when you have some global app wide shortcuts like CMD+Q.
  • isolate: bool
    • Use this when a child component has React's key handler (onKeyUp, onKeyPress, onKeyDown). Otherwise, React Shortcuts stops propagation of that event due to nature of event delegation that React uses internally.
  • alwaysFireHandler: bool
    • Use this when you want events keep firing on the focused input elements.

Thanks, Atom

This library is inspired by Atom Keymap.