react-hotkeys-hook vs react-hotkeys vs react-hot-keys
React Hotkey Libraries Comparison
1 Year
react-hotkeys-hookreact-hotkeysreact-hot-keysSimilar Packages:
What's React Hotkey Libraries?

React hotkey libraries provide a way to handle keyboard shortcuts within React applications. They allow developers to define key combinations that trigger specific actions, improving the user experience by enabling faster navigation and interaction. These libraries are particularly useful for applications that require complex keyboard interactions, such as text editors, data entry forms, or any interface where efficiency is key. By using hotkeys, developers can create more accessible and intuitive applications, allowing users to perform tasks quickly without relying solely on mouse interactions.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-hotkeys-hook1,007,5253,14734.8 kB382 months agoMIT
react-hotkeys450,3502,163-1086 years agoISC
react-hot-keys15,89042949.4 kB212 years agoMIT
Feature Comparison: react-hotkeys-hook vs react-hotkeys vs react-hot-keys

API Design

  • react-hotkeys-hook:

    react-hotkeys-hook provides a simple and clean API for defining hotkeys using React hooks. It allows you to create hotkeys directly within your functional components, promoting a more modern and declarative approach to handling keyboard events. The API is lightweight and easy to use, making it a great choice for developers familiar with hooks.

  • react-hotkeys:

    react-hotkeys offers a more comprehensive API that supports nested key handlers and dynamic key mapping. It allows for greater flexibility in defining hotkeys, including the ability to create context-aware key handlers. The API is well-documented, but the added complexity may require a bit more time to fully understand and utilize all its features.

  • react-hot-keys:

    react-hot-keys provides a straightforward API for defining hotkeys within your components. It uses a simple HotKeys component to wrap around the part of your application where you want to listen for key events. The API is intuitive and easy to understand, making it quick to implement basic hotkey functionality.

Complexity

  • react-hotkeys-hook:

    react-hotkeys-hook strikes a balance between simplicity and functionality. It is lightweight and easy to use, making it ideal for modern React applications that utilize hooks. While it may not have all the advanced features of react-hotkeys, it provides enough functionality for most use cases without unnecessary complexity.

  • react-hotkeys:

    react-hotkeys is more complex and feature-rich, making it suitable for applications that require advanced hotkey management, including support for nested key handlers and dynamic key mapping. This complexity allows for greater flexibility and customization but may require more time to implement and manage effectively.

  • react-hot-keys:

    react-hot-keys is designed for simplicity and ease of use. It is best suited for applications that require basic hotkey functionality without the need for complex configurations or nested key handlers. The library's straightforward design makes it easy to integrate into any project quickly.

Accessibility

  • react-hotkeys-hook:

    react-hotkeys-hook is designed with accessibility in mind, providing a simple way to define hotkeys that can be easily integrated into accessible components. However, like any hotkey library, it is important for developers to ensure that the hotkeys they implement do not interfere with native accessibility features and are usable by all users.

  • react-hotkeys:

    react-hotkeys places a stronger emphasis on accessibility, particularly with its support for nested key handlers and context-aware key mapping. The library is designed to be more inclusive, making it a better choice for applications that prioritize accessibility and need to accommodate a wider range of users.

  • react-hot-keys:

    react-hot-keys provides basic accessibility features, but it is primarily focused on functionality rather than comprehensive accessibility support. Developers may need to implement additional accessibility features manually to ensure that hotkeys are usable by all users, including those with disabilities.

Code Example

  • react-hotkeys-hook:

    Simple Example with react-hotkeys-hook

    import React from 'react';
    import { useHotkeys } from 'react-hotkeys-hook';
    
    const App = () => {
      useHotkeys('ctrl+s', () => alert('Save action!'));
      useHotkeys('del', () => alert('Delete action!'));
    
      return (
        <div>
          <h1>React Hotkeys Hook Example</h1>
          <p>Press Ctrl+S to save or Delete to trigger actions.</p>
        </div>
      );
    };
    
    export default App;
    
  • react-hotkeys:

    Advanced Example with react-hotkeys

    import React from 'react';
    import { HotKeys } from 'react-hotkeys';
    
    const App = () => {
      const keyMap = {
        SAVE: 'ctrl+s',
        DELETE: 'del',
        NESTED: {  // Nested key mapping
          key: 'n',
          handlers: { NESTED_ACTION: 'enter' },
        },
      };
    
      const handlers = {
        SAVE: () => alert('Save action!'),
        DELETE: () => alert('Delete action!'),
        NESTED_ACTION: () => alert('Nested action!'),
      };
    
      return (
        <HotKeys keyMap={keyMap} handlers={handlers}>
          <div>
            <h1>React Hotkeys Example</h1>
            <p>Press Ctrl+S to save, Delete to delete, or N to trigger nested actions.</p>
          </div>
        </HotKeys>
      );
    };
    
    export default App;
    
  • react-hot-keys:

    Basic Example with react-hot-keys

    import React from 'react';
    import { HotKeys } from 'react-hot-keys';
    
    const App = () => {
      const keyMap = {
        SAVE: 'ctrl+s',
        DELETE: 'del',
      };
    
      const handlers = {
        SAVE: () => alert('Save action!'),
        DELETE: () => alert('Delete action!'),
      };
    
      return (
        <HotKeys keyMap={keyMap} handlers={handlers}>
          <div>
            <h1>React Hot Keys Example</h1>
            <p>Press Ctrl+S to save or Delete to trigger actions.</p>
          </div>
        </HotKeys>
      );
    };
    
    export default App;
    
How to Choose: react-hotkeys-hook vs react-hotkeys vs react-hot-keys
  • react-hotkeys-hook:

    Opt for react-hotkeys-hook if you prefer a hook-based approach to managing hotkeys in functional components. This library is lightweight and provides a simple API for defining hotkeys, making it a great choice for modern React applications that utilize hooks.

  • react-hotkeys:

    Select react-hotkeys if you need a more feature-rich library that supports nested key handlers, key mapping, and dynamic key bindings. This library is suitable for applications that require more complex keyboard interactions and offer better support for accessibility and customization.

  • react-hot-keys:

    Choose react-hot-keys if you need a simple and lightweight solution for handling keyboard shortcuts in your React application. It is easy to set up and use, making it ideal for projects that require basic hotkey functionality without a lot of overhead.

README for react-hotkeys-hook

useHotkeys(keys, callback)

Bundlephobia Types NPM Version MIT License

Sponsored by Spaceteams

npm i react-hotkeys-hook

A React hook for using keyboard shortcuts in components in a declarative way.


Quick Start

The easiest way to use the hook.

import { useHotkeys } from 'react-hotkeys-hook'

export const ExampleComponent = () => {
  const [count, setCount] = useState(0)
  useHotkeys('ctrl+k', () => setCount(count + 1), [count])

  return (
    <p>
      Pressed {count} times.
    </p>
  )
}

Scopes

Scopes allow you to group hotkeys together. You can use scopes to prevent hotkeys from colliding with each other.

const App = () => {
  return (
    <HotkeysProvider initiallyActiveScopes={['settings']}>
      <ExampleComponent />
    </HotkeysProvider>
  )
}

export const ExampleComponent = () => {
  const [count, setCount] = useState(0)
  useHotkeys('ctrl+k', () => setCount(prevCount => prevCount + 1), { scopes: ['settings'] })

  return (
    <p>
      Pressed {count} times.
    </p>
  )
}

Changing a scope's active state

You can change the active state of a scope using the disableScope, enableScope and toggleScope functions returned by the useHotkeysContext() hook. Note that you have to have your app wrapped in a <HotkeysProvider> component.

const App = () => {
  return (
    <HotkeysProvider initiallyActiveScopes={['settings']}>
      <ExampleComponent />
    </HotkeysProvider>
  )
}

export const ExampleComponent = () => {
  const { toggleScope } = useHotkeysContext()

  return (
    <button onClick={() => toggleScope('settings')}>
      Change scope active state
    </button>
  )
}

Focus trap

This will only trigger the hotkey if the component is focused.

export const ExampleComponent = () => {
  const [count, setCount] = useState(0)
  const ref = useHotkeys<HTMLParagraphElement>('ctrl+k', () => setCount(prevCount => prevCount + 1))

  return (
    <p tabIndex={-1} ref={ref}>
      Pressed {count} times.
    </p>
  )
}

Documentation & Live Examples

API

useHotkeys(keys, callback)

useHotkeys(keys: string | string[], callback: (event: KeyboardEvent, handler: HotkeysEvent) => void, options: Options = {}, deps: DependencyList = [])

| Parameter | Type | Required? | Default value | Description | |---------------|---------------------------------------------------------|-----------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | keys | string or string[] | required | - | set the hotkeys you want the hook to listen to. You can use single or multiple keys, modifier combinations, etc. This will either be a string or an array of strings. To separate multiple keys, use a comma. This split key value can be overridden with the splitKey option. | | callback | (event: KeyboardEvent, handler: HotkeysEvent) => void | required | - | This is the callback function that will be called when the hotkey is pressed. The callback will receive the browsers native KeyboardEvent and the libraries HotkeysEvent. | | options | Options | optional | {} | Object to modify the behavior of the hook. Default options are given below. | | dependencies | DependencyList | optional | [] | The given callback will always be memoised inside the hook. So if you reference any outside variables, you need to set them here for the callback to get updated (Much like useCallback works in React). |

Options

All options are optional and have a default value which you can override to change the behavior of the hook.

| Option | Type | Default value | Description | |--------------------------|--------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | enabled | boolean or (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => boolean | true | This option determines whether the hotkey is active or not. It can take a boolean (for example a flag from a state outside) or a function which gets executed once the hotkey is pressed. If the function returns false the hotkey won't get executed and all browser events are prevented. | | enableOnFormTags | boolean or FormTags[] | false | By default hotkeys are not registered if a focus focuses on an input field. This will prevent accidental triggering of hotkeys when the user is typing. If you want to enable hotkeys, use this option. Setting it to true will enable on all form tags, otherwise you can give an array of form tags to enable the hotkey on (possible options are: ['input', 'textarea', 'select']) | | enableOnContentEditable | boolean | false | Set this option to enable hotkeys on tags that have set the contentEditable prop to true | | combinationKey | string | + | Character to indicate keystrokes like shift+c. You might want to change this if you want to listen to the + character like ctrl-+. | | splitKey | string | , | Character to separate different keystrokes like ctrl+a, ctrl+b. | | scopes | string or string[] | * | With scopes you can group hotkeys together. The default scope is the wildcard * which matches all hotkeys. Use the <HotkeysProvider> component to change active scopes. | | keyup | boolean | false | Determines whether to listen to the browsers keyup event for triggering the callback. | | keydown | boolean | true | Determines whether to listen to the browsers keydown event for triggering the callback. If you set both keyupand keydown to true, the callback will trigger on both events. | | preventDefault | boolean or (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => boolean | false | Set this to a true if you want the hook to prevent the browsers default behavior on certain keystrokes like meta+s to save a page. NOTE: Certain keystrokes are not preventable, like meta+w to close a tab in chrome. | | description | string | undefined | Use this option to describe what the hotkey does. this is helpful if you want to display a list of active hotkeys to the user. |

Overloads

The hooks call signature is very flexible. For example if you don't need to set any special options you can use the dependency array as your third parameter:

useHotkeys('ctrl+k', () => console.log(counter + 1), [counter])

isHotkeyPressed(keys: string | string[], splitKey?: string = ',')

This function allows us to check if the user is currently pressing down a key.

import { isHotkeyPressed } from 'react-hotkeys-hook'

isHotkeyPressed('esc') // Returns true if Escape key is pressed down.

You can also check for multiple keys at the same time:

isHotkeyPressed(['esc', 'ctrl+s']) // Returns true if Escape or Ctrl+S are pressed down.

Support

Found an issue or have a feature request?

Open up an issue or pull request and participate.

Local Development

Checkout this repo, run yarn or npm i and then run the test script to test the behavior of the hook.

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Johannes Klauss - @JohannesKlauss - klauss.johannes@gmail.com

Project Link: https://github.com/JohannesKlauss/react-hotkeys-hook

Contributors