use-hotkeys

React hook for using keyboard shortcuts in components.

README


    useHotkeys(keys, callback)


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.

  1. ```jsx harmony
  2. import { useHotkeys } from 'react-hotkeys-hook'

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

  6.   return (
  7.     <p>
  8.       Pressed {count} times.
  9.     </p>
  10.   )
  11. }
  12. ```

Scopes


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

  1. ```jsx harmony
  2. const App = () => {
  3.   return (
  4.     <HotkeysProvider initiallyActiveScopes={['settings']}>
  5.       <ExampleComponent />
  6.     </HotkeysProvider>
  7.   )
  8. }

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

  12.   return (
  13.     <p>
  14.       Pressed {count} times.
  15.     </p>
  16.   )
  17. }
  18. ```

Changing a scope's active state


You can change the active state of a scope using the deactivateScope, activateScope and toggleScope functions
returned by the `useHotkeysContext()` hook. Note that you have to have your app wrapped in a `` component.

  1. ```jsx harmony
  2. const App = () => {
  3.   return (
  4.     <HotkeysProvider initiallyActiveScopes={['settings']}>
  5.       <ExampleComponent />
  6.     </HotkeysProvider>
  7.   )
  8. }

  9. export const ExampleComponent = () => {
  10.   const { toggleScope } = useHotkeysContext()

  11.   return (
  12.     <button onClick={() => toggleScope('settings')}>
  13.       Change scope active state
  14.     </button>
  15.   )
  16. }
  17. ```

Focus trap


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

  1. ```tsx harmony
  2. export const ExampleComponent = () => {
  3.   const [count, setCount] = useState(0)
  4.   const ref = useHotkeys<HTMLParagraphElement>('ctrl+k', () => setCount(prevCount => prevCount + 1))

  5.   return (
  6.     <p tabIndex={-1} ref={ref}>
  7.       Pressed {count} times.
  8.     </p>
  9.   )
  10. }
  11. ```

Documentation & Live Examples



API


useHotkeys(keys, callback)


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

ParameterTypeRequired?DefaultDescription
|---------------|---------------------------------------------------------|-----------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
`keys``string`required-set
`callback``(event:required-This
`options``Options`optional`{}`Object
`dependencies``DependencyList`optional`[]`The

Options


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

OptionTypeDefaultDescription
|--------------------------|--------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
`enabled``boolean``true`This
`enableOnFormTags``boolean``false`By
`enableOnContentEditable``boolean``false`Set
`combinationKey``string``+`Character
`splitKey``string``,`Character
`scopes``string``*`With
`keyup``boolean``false`Determines
`keydown``boolean``true`Determines
`preventDefault``boolean``false`Set
`description``string``undefined`Use


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.

  1. ```ts
  2. import { isHotkeyPressed } from 'react-hotkeys-hook'

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

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

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

Support


Ask your question in the Github Discussions)
Ask your question on StackOverflow

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


Contributors