Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
react-hotkeys-hook
Advanced tools
The react-hotkeys-hook package is a React hook for handling keyboard shortcuts. It allows developers to easily add keyboard shortcuts to their React applications, making it easier to enhance user interactions and accessibility.
Basic Key Binding
This feature allows you to bind a specific key combination to a function. In this example, pressing 'Ctrl+K' will trigger an alert.
```jsx
import React from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
const App = () => {
useHotkeys('ctrl+k', () => alert('Ctrl+K pressed!'));
return (
<div>
<h1>Press Ctrl+K</h1>
</div>
);
};
export default App;
```
Multiple Key Bindings
This feature allows you to bind multiple key combinations to a single function. In this example, pressing either 'Ctrl+K' or 'Ctrl+L' will trigger an alert.
```jsx
import React from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
const App = () => {
useHotkeys('ctrl+k, ctrl+l', () => alert('Ctrl+K or Ctrl+L pressed!'));
return (
<div>
<h1>Press Ctrl+K or Ctrl+L</h1>
</div>
);
};
export default App;
```
Scoped Key Bindings
This feature allows you to bind key combinations within specific scopes. In this example, 'Ctrl+K' can be bound to different functions in different components or contexts.
```jsx
import React from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
const App = () => {
useHotkeys('ctrl+k', () => alert('Ctrl+K pressed!'), { scopes: ['scope1'] });
return (
<div>
<h1>Press Ctrl+K</h1>
</div>
);
};
const AnotherComponent = () => {
useHotkeys('ctrl+k', () => alert('Ctrl+K pressed in another component!'), { scopes: ['scope2'] });
return (
<div>
<h1>Press Ctrl+K in Another Component</h1>
</div>
);
};
export default App;
```
react-hotkeys is a mature library for handling keyboard shortcuts in React applications. It provides a more comprehensive API for managing key events and supports nested hotkey scopes. Compared to react-hotkeys-hook, it offers more advanced features but may require more setup.
react-shortcuts is another library for handling keyboard shortcuts in React. It focuses on simplicity and ease of use, similar to react-hotkeys-hook. However, it may not offer as many advanced features or customization options as react-hotkeys-hook.
react-keyboard-event-handler is a lightweight library for handling keyboard events in React. It is easy to use and provides basic functionality for key bindings. It is similar to react-hotkeys-hook in terms of simplicity but may lack some of the more advanced features.
npm i react-hotkeys-hook
A React hook for using keyboard shortcuts in components in a declarative way.
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 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>
)
}
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 <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>
)
}
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>
)
}
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 colon. 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). |
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 keyup and 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. |
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.
Open up an issue or pull request and participate.
Checkout this repo, run yarn
or npm i
and then run the test
script to test the behavior of the hook.
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
git checkout -b feature/AmazingFeature
)git commit -m 'Add some AmazingFeature'
)git push origin feature/AmazingFeature
)Distributed under the MIT License. See LICENSE
for more information.
Johannes Klauss - @JohannesKlauss - klauss.johannes@gmail.com
Project Link: https://github.com/JohannesKlauss/react-hotkeys-hook
FAQs
React hook for handling keyboard shortcuts
The npm package react-hotkeys-hook receives a total of 0 weekly downloads. As such, react-hotkeys-hook popularity was classified as not popular.
We found that react-hotkeys-hook demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.