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.
- ```jsx harmony
- 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.
- ```jsx harmony
- 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 deactivateScope, activateScope and toggleScope functions
returned by the `useHotkeysContext()` hook. Note that you have to have your app wrapped in a `- ```jsx harmony
- 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.
- ```tsx harmony
- 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)
- ```typescript
- useHotkeys(keys: string | string[], callback: (event: KeyboardEvent, handler: HotkeysEvent) => void, options: Options = {}, deps: DependencyList = [])
- ```
Parameter | Type | Required? | Default | Description |
---|---|---|---|---|
|---------------|---------------------------------------------------------|-----------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ||||
`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.
Option | Type | Default | Description |
---|---|---|---|
|--------------------------|--------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | |||
`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.
- ```ts
- 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:
- ```ts
- isHotkeyPressed(['esc', 'ctrl+s']) // Returns true if Escape or Ctrl+S are pressed down.
- ```
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
Project Link: https://github.com/JohannesKlauss/react-hotkeys-hook