Gathering detailed insights and metrics for react-hotkeys
Gathering detailed insights and metrics for react-hotkeys
Gathering detailed insights and metrics for react-hotkeys
Gathering detailed insights and metrics for react-hotkeys
Declarative hotkey and focus area management for React
npm install react-hotkeys
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,154 Stars
539 Commits
160 Forks
19 Watching
38 Branches
45 Contributors
Updated on 20 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
9.4%
59,741
Compared to previous day
Last week
3.8%
290,879
Compared to previous week
Last month
15.4%
1,255,920
Compared to previous month
Last year
-38%
15,580,602
Compared to previous year
1
1
39
A declarative library for handling hotkeys and focus areas in React applications.
See the upgrade notes.
This package has been more or less unmaintained for over 6 months and is search of new maintainers to help address the many outstanding issues. If you are interested in helping out in any capacity, please get in touch.
prop-types
and a peer dependency of react
1import { HotKeys } from "react-hotkeys"; 2import MyNode from "./MyNode"; 3import React from 'react'; 4 5const keyMap = { 6 SNAP_LEFT: "command+left", 7 DELETE_NODE: ["del", "backspace"] 8}; 9 10const App = () => { 11 return ( 12 <HotKeys keyMap={keyMap}> 13 <div> 14 <MyNode /> 15 <MyNode /> 16 </div> 17 </HotKeys> 18 ); 19}; 20 21export default App;
1import { HotKeys } from "react-hotkeys"; 2import React from 'react'; 3 4const MyNode = () => { 5 const deleteNode = React.useCallback(() => { 6 // logic here 7 }, []) 8 9 const handlers = { 10 DELETE_NODE: deleteNode 11 }; 12 13 return <HotKeys handlers={handlers}>Node contents</HotKeys>; 14}; 15 16export default MyNode;
react-hotkeys
is released under the ISC License.
However, please note: the source code found in the lib/vendor directory is under the MIT License - please see the license file for each directory for more information.
If you use React Hotkeys and it has saved you time or money, please consider contributing. You will be supporting react-hotkeys
by supporting its maintainer.
Please see my Patreon Page for details of why your support is needed, and how it will be used.
For recurring and publicly acknowledged support:
Payment Option | Link/Address |
---|---|
Patreon | https://www.patreon.com/aleckgreenham |
For one-off or irregular contributions:
Payment Option | Link/Address |
---|---|
Paypal | https://www.paypal.me/aleckgreenham |
Bitcoin | 1ETTdVEahUqBaGXRQaiEgMhVjYQU1jQKKT |
Ethereum | 0x6C9F9879f684e84314f5810f8F196bdB2c4e15c0 |
Stellar | GBJ5T7V7YVRN4D2PBZTOCWREJXYWWGNDIQGRFDGQAZNTYYIW7BMWDRYA |
react-hotkeys
is available as a CommonJS or a ES6 Modules through npm or yarn. It uses NODE_ENV
to determine whether to export the development or production build in your library or application.
It is expected you will use a bundling tool like Webpack or Uglify to remove the version of the bundle you are not using with each version of your application's code, to keep the library size to a minimum.
npm install react-hotkeys@next --save
yarn add react-hotkeys@next
npm install react-hotkeys --save
yarn add react-hotkeys
react-hotkeys
as a UMD module is available on your CDN of choice.
Change 1.0.1
for the version that you would like to use.
<script crossorigin src="https://cdn.jsdelivr.net/npm/react-hotkeys@1.0.1/umd/react-hotkeys.js"></script>
<script crossorigin src="https://unpkg.com/react-hotkeys@1.0.1/umd/react-hotkeys.js"></script>
<script crossorigin src="https://cdn.jsdelivr.net/npm/react-hotkeys@1.0.1/umd/react-hotkeys.min.js"></script>
<script crossorigin src="https://unpkg.com/react-hotkeys@1.0.1/umd/react-hotkeys.min.js"></script>
Bower support was removed in v1.0.0
, but those who already rely on earlier versions of react-hotkeys
through Bower can continue to do so using the following command:
bower install react-hotkeys@0.10.0
The Bower version of the package will not be supported going forward (including fixing any outstanding issues).
react-hotkeys
uses key maps to decouple defining keyboard shortcuts from the functions they call. This allows hot keys and handler functions to be defined and maintained independent of one another.
When a user presses the corresponding combination or sequence of keys, it is said they match the hot keys, which causes an action to be triggered.
react-hotkeys
may then resolve an appropriate handler function to handle the action.
Key maps are Plain Old JavaScript Objects, where the keys are the action names and the values are usually a Mousetrap-supported or Browser Key Values sequence string (but can also be an array or an object) that must be matched in order to trigger the action.
1const keyMap = { 2 deleteNode: "del", 3 moveUp: "up" 4};
Every hotkey or sequence string is parsed and treated as a sequence of key combinations. The simplest case is a sequence of 1 key combination, consisting of 1 key: e.g. 'a'
or 'shift'
.
// Key sequence with a combination of a single key
'4'
// Special single key sequence (ie. shift is handled automagically)
'?'
// Sequence of a single combination with multiple keys (keys must be pressed at the same time)
'command+shift+k'
// Sequence of multiple combinations (keys must be pressed and released one after another)
'up down left right'
Please refer to Mousetrap's documentation or Browser Key Values for an exhaustive list of supported shortcuts and sequences.
You can specify multiple alternative key sequences (they will trigger the same action) using arrays:
1const keyMap = { 2 DELETE_NODE: ["del", "backspace"], 3 MOVE_UP: ["up", "w"] 4};
By default, react-hotkeys
will match hotkey sequences on the keydown
event (or, more precisely: on the keydown
event of the last key to complete the last combination in a sequence).
If you want to trigger a single action on a different key event, you can use the object syntax and the action
attribute to explicitly set which key event you wish to bind to:
1const keyMap = { 2 CONTRACT: "alt+down", 3 COMMAND_DOWN: { sequence: "command", action: "keydown" } 4};
If you want to change the default key event for all hotkeys, you can use the defaultKeyEvent
option of the configuration API.
The full list of valid key events is: keypress
, keydown
, and keyup
.
You can specify data used to display the application's key maps using the object syntax and the name
, description
and group
attributes (each are optional):
1 { 2 SHOW_DIALOG: { 3 name: 'Display keyboard shortcuts', 4 sequence: 'shift+?', 5 action: 'keyup' 6 } 7 }
If you want to also provide alternative key sequences for the same action, use the sequences
attribute:
1 { 2 SHOW_DIALOG: { 3 name: 'Display keyboard shortcuts', 4 sequences: ['shift+?', { sequence: '`', action: 'keyup' }], 5 action: 'keyup' 6 } 7 }
As a general rule, you should use the syntax that is the most brief, but still allows you to express the configuration you want.
Syntax Type | Use when you ... |
---|---|
String | Have a single key sequence and don't have any special requirements (Default case) |
Array of strings | Need alternative key maps that trigger the same action, and are happy with them triggering on the default key event |
Array of objects | Need alternative key maps that trigger the same action, and want to them to trigger on a different key event |
Object | Have a single key sequence and want to specify a different key event or display data |
Object (sequences attribute) | Have multiple key sequences that trigger the same action, and want to specify a different key event or display data |
When you are working in a WebOS environment, or a similar, you may have need to define custom key codes. You can do so using the customKeyCodes
Configuration option:
1 2import {configure} from 'react-hotkeys'; 3 4configure({ 5 customKeyCodes: { 6 10009: 'BackTV' 7 } 8})
Once defined, you are then able to use the key names in you action sequences:
1const keyMap = { 2 MY_ACTION: 'BackTV', 3};
react-hotkeys
has basic support for setting dynamic hotkeys - i.e. letting the user set their own keyboard shortcuts at runtime. Once you have set up the necessary UI for viewing the current keyboard shortcuts (and opting to change them), you can then use the recordKeyCombination
function to capture the keys the user wishes to use.
recordKeyCombination
accepts a callback function that will be called on the last keyup
of the next key combination - immediately after the user has pressed the key combination they wish to assign. The callback then unbinds itself, so you do not have to worry about tidying up after it.
recordKeyCombination
returns a function you can call at any time after binding the listener, to cancel listening without waiting for the key combination to complete.
The callback function receives a single argument with the following schema:
1{ 2 /** 3 * Combination ID that can be passed to the keyMap prop to (re)define an 4 * action's key sequence 5 */ 6 id: '', 7 /** 8 * Dictionary of keys involved in the combination 9 */ 10 keys: { keyName: true } 11} 12 13// Example: 14 15{ 16 id: 'a', 17 keys: { a: true } 18}
If you are updating hotkeys without changing focus or remounting the component that defines them, you will need to make sure you use the allowChanges
prop to ensure the new keymaps are honoured immediately.
An example, rendering two dialogs:
recordKeyCombination()
1import { recordKeyCombination } from 'react-hotkeys'; 2import React from 'react'; 3 4renderDialog(){ 5 if (this.state.showShortcutsDialog) { 6 const keyMap = getApplicationKeyMap(); 7 8 return ( 9 <div style={styles.DIALOG}> 10 <h2> 11 Keyboard shortcuts 12 </h2> 13 14 <table> 15 <tbody> 16 { 17 Object.keys(keyMap).reduce((memo, actionName) => { 18 const { sequences, name } = keyMap[actionName]; 19 20 memo.push( 21 <tr key={name || actionName}> 22 <td style={styles.KEYMAP_TABLE_CELL}> 23 { name } 24 </td> 25 <td style={styles.KEYMAP_TABLE_CELL}> 26 { sequences.map(({sequence}) => <span key={sequence}>{sequence}</span>) } 27 </td> 28 <td style={styles.KEYMAP_TABLE_CELL}> 29 <button onClick={ () => this.showChangeShortcutDialog(actionName) }> 30 Change 31 </button> 32 </td> 33 </tr> 34 ); 35 36 return memo; 37 }) 38 } 39 </tbody> 40 </table> 41 </div> 42 ); 43 } else if (this.state.changingActionShortcut) { 44 const { cancel } = this.state.changingActionShortcut; 45 46 const keyMap = getApplicationKeyMap(); 47 const { name } = keyMap[this.state.changingActionShortcut]; 48 49 return ( 50 <div style={styles.DIALOG}> 51 Press the keys you would like to bind to #{name}. 52 53 <button onClick={cancel}> 54 Cancel 55 </button> 56 </div> 57 ); 58 } 59} 60 61showChangeShortcutDialog(actionName) { 62 const cancelListening = recordKeyCombination(({id}) => { 63 this.setState({ 64 showShortcutsDialog: true, 65 changingActionShortcut: null, 66 keyMap: { 67 ...this.state.keyMap, 68 [actionName]: id 69 } 70 }); 71 }); 72 73 this.setState({ 74 showShortcutsDialog: false, 75 changingActionShortcut: { 76 cancel: () => { 77 cancelListening(); 78 79 this.setState({ 80 showShortcutsDialog: true, 81 changingActionShortcut: null 82 }); 83 } 84 } 85 }); 86}
Key maps trigger actions when they match a key sequence. Handlers are the functions that react-hotkeys
calls to handle those actions.
Handlers may be defined in the same <HotKeys />
component as the key map:
1import { HotKeys } from "react-hotkeys"; 2import React from 'react'; 3 4const keyMap = { 5 MOVE_UP: "up" 6}; 7 8const handlers = { 9 MOVE_UP: event => console.log("Move up hotkey called!") 10}; 11 12<HotKeys keyMap={keyMap} handlers={handlers}> 13 <input /> 14</HotKeys>;
Or they may be defined in any descendant of the <HotKeys />
component that defines the key map:
1import { HotKeys } from "react-hotkeys"; 2import React from 'react'; 3 4const keyMap = { 5 MOVE_UP: "up" 6}; 7 8const handlers = { 9 MOVE_UP: event => console.log("Move up hotkey called!") 10}; 11 12<HotKeys keyMap={keyMap}> 13 <div> 14 <HotKeys handlers={handlers}> 15 <input /> 16 </HotKeys> 17 </div> 18 19 <div> 20 <input /> 21 </div> 22</HotKeys>;
Rather than re-invent the wheel, react-hotkeys
piggy-backs of the React SyntheticEvent and event propagation, so all of the normal React behaviour that you expect still applies.
stopPropagation()
called on it, it will not be seen by components higher up in the render tree.<HotKeys>
components listen only to key events that happen when one of their DOM-mounted descendents are in focus (<div/>
, <span/>
, <input/>
, etc). This emulates (and re-uses) the behaviour of the browser and React's SyntheticEvent propagation.
This is the default type of <HotKeys />
component, and should normally be your first choice for efficiency and clarity (the user generally expects keyboard input to affect the focused element in the browser).
The HotKeys component provides a declarative and native JSX syntax that is best for succinctly declaring hotkeys in a way that best maintains separation and encapsulation with regards to the rest of your code base.
However, it does require that its children be wrapped in a DOM-mounted node, which can break styling and add extra levels to your render tree.
1 2<HotKeys 3 /** 4 * An object that defines actions as keys and key sequences as values 5 * (using either a string, array or object). 6 * 7 * Actions defined in one HotKeys component are available to be handled 8 * in an descendent HotKeys component. 9 * 10 * Optional. 11 */ 12 keyMap={ {} } 13 14 /** 15 * An object that defines handler functions as values, and the actions 16 * that they handle as keys. 17 * 18 * Optional. 19 */ 20 handlers={ {} } 21 22 /** 23 * The type of DOM-mountable component that should be used to wrap 24 * the component's children. 25 */ 26 component={ 'div' } 27 28 /** 29 * tabindex value to pass to DOM-mountable component wrapping children 30 */ 31 tabIndex={-1} 32 33 /** 34 * Whether the keyMap or handlers are permitted to change after the 35 * component mounts. If false, changes to the keyMap and handlers 36 * props will be ignored 37 * 38 * Optional. 39 */ 40 allowChanges={false} 41 42 /** 43 * A ref to add to the underlying DOM-mountable node. Pass a function 44 * to get a reference to the node, so you can call .focus() on it 45 */ 46 innerRef: {undefined} 47 48 /** 49 * Whether this is the root HotKeys node - this enables some special 50 * behaviour 51 */ 52 root={false} 53 > 54 55 /** 56 * Wraps all children in a DOM-mountable component 57 */ 58 { children } 59 60</HotKeys>
The HotKeys component API is generally recommended, but if wrapping your component in a DOM-mountable node is not acceptable, or you need more control over how the react-hotkeys
props are applied, then the withHotKeys()
HoC is available.
The simplest use-case of withHotKeys()
is to simply pass it your component class as the first argument. What is returned is a new component that will accept all of the same props as a <HotKey>
component, so you can specify key maps and handlers at render time, for example.
The component you wrap must take responsibility for passing the
hotKeys
props to a DOM-mountable element. If you fail to do this, key events will not be detected when a descendant of the component is in focus.
1import { withHotKeys } from "react-hotkeys"; 2 3class MyComponent extends Component { 4 render() { 5 /** 6 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 7 * element (like the div below). 8 */ 9 const { hotKeys, ...remainingProps } = this.props; 10 11 return ( 12 <div {...{ ...hotKeys, ...remainingProps }}> 13 <span>My HotKeys are effective here</span> 14 15 {this.props.children} 16 </div> 17 ); 18 } 19} 20 21const MyHotKeysComponent = withHotKeys(MyComponent); 22 23const keyMap = { 24 TEST: "t" 25}; 26 27const handlers = { 28 TEST: () => console.log("Test") 29}; 30 31<MyHotKeysComponent keyMap={keyMap} handlers={handlers}> 32 <div>You can press 't' to log to the console.</div> 33</MyHotKeysComponent>;
You can use the second argument of withHotKeys
to specify default values for any props you would normally pass to <HotKeys />
. This means you do not have to specify them at render-time.
If you do provide prop values when you render the component, these will be merged with (and override) those defined in the second argument of
withHotKeys
.
1import { withHotKeys } from "react-hotkeys"; 2import React from 'react'; 3 4class MyComponent extends Component { 5 render() { 6 /** 7 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 8 * element (like the div below). 9 */ 10 const { hotKeys, ...remainingProps } = this.props; 11 12 return ( 13 <div {...{ ...hotKeys, ...remainingProps }}> 14 <span>My HotKeys are effective here</span> 15 16 {this.props.children} 17 </div> 18 ); 19 } 20} 21 22const keyMap = { 23 TEST: "t" 24}; 25 26const handlers = { 27 TEST: () => console.log("Test") 28}; 29 30const MyHotKeysComponent = withHotKeys(MyComponent, { keyMap, handlers }); 31 32/** 33 * Render without having to specify prop values 34 */ 35<MyHotKeysComponent> 36 <div>You can press 't' to log to the console.</div> 37</MyHotKeysComponent>;
<GlobalHotKeys>
components match key events that occur anywhere in the document (even when no part of your React application is in focus).
1const keyMap = { SHOW_ALL_HOTKEYS: "shift+?" }; 2const handlers = { SHOW_ALL_HOTKEYS: this.showHotKeysDialog }; 3 4<GlobalHotKeys keyMap={keyMap} handlers={handlers} />;
<GlobalHotKeys>
generally have no need for children, so should use a self-closing tag (as shown above). The only exception is when you are nesting other <GlobalHotKeys>
components somewhere in the descendents (these are mounted before their parents, and so are generally matched first).
The GlobalHotKeys component provides a declarative and native JSX syntax for defining hotkeys that are applicable beyond you React application.
1<GlobalHotKeys 2 /** 3 * An object that defines actions as keys and key sequences as values 4 * (using either a string, array or object). 5 * 6 * Actions defined in one HotKeys component are available to be handled 7 * in an descendent HotKeys component. 8 * 9 * Optional. 10 */ 11 keyMap={{}} 12 /** 13 * An object that defines handler functions as values, and the actions 14 * that they handle as keys. 15 * 16 * Optional. 17 */ 18 handlers={{}} 19 /** 20 * Whether the keyMap or handlers are permitted to change after the 21 * component mounts. If false, changes to the keyMap and handlers 22 * props will be ignored 23 * 24 * Optional. 25 */ 26 allowChanges={false} 27> 28 /** * Wraps all children in a DOM-mountable component */ 29 {children} 30</GlobalHotKeys>
For keymaps defined with <HotKeys/>
components, how close your <HotKeys/>
component is to the element currently focused in the DOM has the greatest affect on how actions are resolved. Whenever a key event occurs (keydown
, keypress
or keyup
), react-hotkeys
starts at the <HotKeys/>
component closest to the event's target (the focused element in the browser) and searches up through the hierarchy of focused <HotKeys/>
components, examining each keyMap
for actions for which the current key completes the specified combination or sequence.
Regardless of where <GlobalHotKeys>
components appear in the render tree, they are matched with key events after the event has finished propagating through the React app (if the event originated in the React at all). This means if your React app is in focus and it handles a key event, it will be ignored by the <GlobalHotKeys>
components.
The order used for resolving actions and handlers amongst <GlobalHotKeys>
components, is the order in which they mounted (those mounted first, are given the chance to handle an action first). When a <GlobalHotKeys>
component is unmounted, it is removed from consideration. This can get less deterministic over the course of a long session using a React app as components mount and unmount, so it is best to define actions and handlers that are globally unique.
It is recommended to use <HotKeys>
components whenever possible for better performance and reliability.
You can use the autofocus attributes or programmatically manage focus to automatically focus your React app so the user doesn't have to select it in order for hot keys to take effect. It is common practice to place a
<HotKeys>
component towards the top of your application to match hot keys across your entire React application.
For key combinations, the action only matches if the key is the last one needed to complete the combination. For sequences, the action matches for the last key to complete the last combination in the sequence.
By default, sub-matches are disabled so if you have two actions bound to cmd+a
and a
, and you press the cmd
key and then the a
key (without releasing the cmd
key), then the cmd+a
combination is matched. This allows you to define longer, application-wide key combinations at the top of your app, without them being hidden by shorter context-dependent combinations in different parts of your app. However, it does depend on the order the keys are pressed: in the above example, if a
was pressed first and then cmd
, the a
action would be matched. The trade-off for this behaviour is that combinations are not permitted to overlap: if you have two actions bound to a
and b
and the user presses a
and then b
without first releasing a
, only the action associated with a
will be called (because there are no actions associated with a+b
). If you want allow sub-matches, you can use the allowCombinationSubmatches
configuration option.
The match occurs on the key event you have specified when defining your keymap (the default is keydown
if you have not overridden the defaultKeyEvent
configuration option).
Once a matching action is found, react-hotkeys
then searches for the corresponding action handler.
If one of the DOM-mounted descendents of an
<HotKeys>
component are in focus (and it is listening to key events) AND those key events match a hot key in the component's key map, then the corresponding action is triggered.
react-hotkeys
starts at the <HotKeys/>
component closest to the event's target (the element that was in focus when the key was pressed) and works its way up through the component tree of focused <HotKeys/>
components, looking for a matching handler for the action. The handler closest to the event target AND a descendant of the <HotKeys/>
component that defines the action (or the component itself), is the one that is called.
That is:
<HotKeys>
component is in focus, the component's actions are not matched<HotKeys>
component is nested within the <HotKeys/>
component that defines the action (or is the same <HotKeys />
component), its handler is not called<HotKeys />
component closer to the event target has defined a handler for the same action, a <HotKeys />
component's handler won't be called (the closer component's handler will)A more exhaustive enumeration of react-hotkeys
behaviour can be found by reviewing the test suite.
react-hotkeys
provides the getApplicationKeyMap()
function for getting a mapping of all actions and key sequences that have been defined by components that are currently mounted.
They are returned as an object, with the action names as keys, and the values are objects describing the key map.
Regardless of which syntax you used to define the keymap, they always appear in the following format:
{
ACTION_NAME: {
/**
* Optional attributes - only present if you defined them
*/
name: 'name',
group: 'group',
description: 'description',
/**
* Attributes always present
* /
sequences: [
{
action: 'keydown',
sequence: 'alt+s'
},
// ...
]
},
// ...
}
Below is how the example application renders a dialog of all available hot keys:
1import { getApplicationKeyMap } from 'react-hotkeys'; 2import React from 'react'; 3 4// ... 5 6renderDialog(){ 7 if (this.state.showDialog) { 8 const keyMap = getApplicationKeyMap(); 9 10 return ( 11 <div style={styles.DIALOG}> 12 <h2> 13 Keyboard shortcuts 14 </h2> 15 16 <table> 17 <tbody> 18 { Object.keys(keyMap).reduce((memo, actionName) => { 19 const { sequences, name } = keyMap[actionName]; 20 21 memo.push( 22 <tr key={name || actionName}> 23 <td style={styles.KEYMAP_TABLE_CELL}> 24 { name } 25 </td> 26 <td style={styles.KEYMAP_TABLE_CELL}> 27 { sequences.map(({sequence}) => <span key={sequence}>{sequence}</span>) } 28 </td> 29 </tr> 30 ); 31 32 return memo; 33 }) 34 } 35 </tbody> 36 </table> 37 </div> 38 ); 39 } 40}
For performance reasons, by default react-hotkeys
takes the keyMap
and handlers
prop values when <HotKeys>
components are focused and when <GlobalHotKeys>
components are mounted. It ignores all subsequent updates
to their values when these props change.
If you need the ability to change them while <HotKeys>
are still in focus, or while <GlobalHotKeys>
are still mounted, then you can pass the allowChanges
prop, permitting this behaviour for the particular component.
If you need to do this for all your <HotKeys>
and <GlobalHotKeys>
components, you can use the ignoreKeymapAndHandlerChangesByDefault
option for the Configuration API. This should normally never be done, as it can have significant performance implications.
By default, all key events that originate from <input>
, <select>
or <textarea>
, or have a isContentEditable
attribute of true
are ignored by react-hotkeys
.
If this is not what you want for your application, you can modify the list of tags using the ignoreTags
configuration option or if you need additional control, you can specify a brand new function using the ignoreEventsCondition
configuration option.
If you want an exception to the global ignore policy for a particular part of your app, then you can use the ObserveKeys component.
When a keyboard event occurs, two things happen:
When you ignore an event, if it's a keydown event (a new key is being pressed), it is not added to the key history and no attempt is made to match it against your hotkeys. If it's a keypress or a keyup event and the key already exists in the history, the event is recorded (the key is being released) but no attempt is made to find a corresponding hotkey.
This effectively means, no new ignored keys are recorded and any keys that are already pressed are recorded as being released so they don't bleed into subsequent key combinations.
You only need this component if you want to add extra key events to ignore, that are not already matched by
ignoreEventsCondition()
.
If you want react-hotkeys
to ignore key events coming from a particular area of your app when it is in focus, you can use the <IgnoreKeys/>
component:
1import { IgnoreKeys } from "react-hotkeys"; 2import React from 'react'; 3 4<IgnoreKeys> 5 /** * Children that, when in focus, should have its key events ignored by * 6 react hotkeys */ 7</IgnoreKeys>;
By default, <IgnoreKeys />
will ignore all key events, but you can customize this behaviour by providing a whitelist or blacklist of events to ignore:
1<IgnoreKeys 2 /** 3 * The whitelist of keys that keyevents should be ignored. i.e. if you place 4 * a key in this list, all events related to it will be ignored by react 5 * hotkeys. 6 * 7 * Accepts a string or an array of strings. 8 */ 9 only: { [] } 10 11 /** 12 * The blacklist of keys that keyevents should be not ignored. i.e. 13 * if you place a key in this list, all events related to it will be 14 * still be observed by react hotkeys 15 */ 16 except: { [] } 17 > 18 19 /** 20 * Children that, when in focus, should have its key events ignored by 21 * react hotkeys 22 */ 23 24 { children } 25 26</IgnoreKeys>
Similar to the <HotKeys>
's withHotKeys()
function, there is a withIgnoreKeys()
function for achieving the <IgnoreKeys>
functionality, without the need for rendering a surrounding DOM-mountable element.
1import { withHotKeysIgnore } from "react-hotkeys"; 2import React from 'react'; 3 4class MyComponent extends Component { 5 render() { 6 /** 7 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 8 * element (like the div below). 9 */ 10 const { hotKeys, ...remainingProps } = this.props; 11 12 return ( 13 <div {...{ ...hotKeys, ...remainingProps }}> 14 <span>HotKeys ignores key events from here</span> 15 16 {this.props.children} 17 </div> 18 ); 19 } 20} 21 22const MyHotKeysComponent = withHotKeysIgnore(MyComponent); 23 24<MyHotKeysComponent except={"Escape"}> 25 <div>All key events except the 'Escape' key are ignored here</div> 26</MyHotKeysComponent>;
withIgnoreKeys()
also accepts a second argument that becomes the default props of the component it returns:
1import { withHotKeysIgnore } from "react-hotkeys"; 2import React from 'react'; 3 4class MyComponent extends Component { 5 render() { 6 /** 7 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 8 * element (like the div below). 9 */ 10 const { hotKeys, ...remainingProps } = this.props; 11 12 return ( 13 <div {...{ ...hotKeys, ...remainingProps }}> 14 <span>HotKeys ignores key events from here</span> 15 16 {this.props.children} 17 </div> 18 ); 19 } 20} 21 22const MyHotKeysComponent = withHotKeysIgnore(MyComponent, { except: "Escape" }); 23 24<MyHotKeysComponent> 25 <div>All key events except the 'Escape' key are ignored here</div> 26</MyHotKeysComponent>;
You only need this component if you want to add exceptions to the key events that are matched by
ignoreEventsCondition()
(i.e. you want to observe key events, even though they are globally ignored by default).
If you want react-hotkeys
to always observe key events coming from a particular area of your app when it is in focus (despite the global ignoreEventsCondition
), you can use the <ObserveKeys/>
component:
1import {ObserveKeys} from 'react-hotkeys'; 2import React from 'react'; 3 4<ObserveKeys> 5 /** 6 * Children that, when in focus, should have its key events always 7 * observed by react hotkeys 8 */ 9</ObserveKeys>
By default, <ObserveKeys />
will force all key events to be observed, but you can customize this behaviour by providing a whitelist or blacklist of events to ignore:
1<ObserveKeys 2 /** 3 * The whitelist of keys that keyevents should be forced to be observed. 4 * i.e. if you place a key in this list, all events related to it will be 5 * observed by react hotkeys - even if it's ignored by the 6 * ignoreEventsCondition. 7 * 8 * Accepts a string or an array of strings. 9 */ 10 only: { [] } 11 12 /** 13 * The blacklist of keys that keyevents should be forced to be observed. 14 * i.e. if you place a key in this list, all events related to it will be 15 * still be ignored by react hotkeys if they match ignoreEventsCondition 16 */ 17 except: { [] } 18 > 19 20 /** 21 * Children that, when in focus, should have its key events observed by 22 * react hotkeys - even if they match ignoreEventsCondition 23 */ 24 25 { children } 26 27</ObserveKeys>
Similar to the <HotKeys>
's withHotKeys()
function, there is a withObserveKeys()
function for achieving the <ObserveKeys>
functionality, without the need for rendering a surrounding DOM-mountable element.
1import {withObserveKeys} from 'react-hotkeys'; 2import React from 'react'; 3 4class MyComponent extends Component { 5 render() { 6 /** 7 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 8 * element (like the div below). 9 */ 10 const {hotKeys, ...remainingProps} = this.props; 11 12 return ( 13 <div { ... { ...hotKeys, ...remainingProps } } > 14 <span>HotKeys always observes key events from here</span> 15 16 { this.props.children } 17 </div> 18 ) 19 } 20} 21 22const MyHotKeysComponent = withObserveKeys(MyComponent); 23 24<MyHotKeysComponent except={ 'Escape' }> 25 <div> 26 All key events except the 'Escape' key are observed here 27 </div> 28</MyHotKeysComponent>
withObserveKeys()
also accepts a second argument that becomes the default props of the component it returns:
1import {withObserveKeys} from 'react-hotkeys'; 2import React from 'react'; 3 4class MyComponent extends Component { 5 render() { 6 /** 7 * Must unwrap hotKeys prop and pass its values to a DOM-mountable 8 * element (like the div below). 9 */ 10 const {hotKeys, ...remainingProps} = this.props; 11 12 return ( 13 <div { ... { ...hotKeys, ...remainingProps } } > 14 <span>HotKeys observes key events from here</span> 15 16 { this.props.children } 17 </div> 18 ) 19 } 20} 21 22const MyHotKeysComponent = withObserveKeys(MyComponent, { except: 'Escape' }); 23 24<MyHotKeysComponent> 25 <div> 26 All key events that match the ignoreEventsCondition are still observed here, except the 'Escape' key 27 </div> 28</MyHotKeysComponent>
The default behaviour across all <HotKeys>
components is configured using the configure
method.
configure() should be called as your app is initialising and before the first time you mount a
<HotKeys>
component anywhere your app.
The following options are available (default values are shown):
1import {configure} from 'react-hotkeys'; 2 3configure({ 4 /** 5 * The level of logging of its own behaviour React HotKeys should perform. 6 */ 7 logLevel: 'warn', 8 9 /** 10 * Default key event key maps are bound to (keydown|keypress|keyup) 11 */ 12 defaultKeyEvent: 'keydown', 13 14 /** 15 * The default component type to wrap HotKey components' children in, to provide 16 * the required focus and keyboard event listening for HotKeys to function 17 */ 18 defaultComponent: 'div', 19 20 /** 21 * The default tabIndex value passed to the wrapping component used to contain 22 * HotKey components' children. -1 skips focusing the element when tabbing through 23 * the DOM, but allows focusing programmatically. 24 */ 25 defaultTabIndex: '-1', 26 27 /** 28 * The HTML tags that React HotKeys should ignore key events from. This only works 29 * if you are using the default ignoreEventsCondition function. 30 * @type {String[]} 31 */ 32 ignoreTags: ['input', 'select', 'textarea'], 33 34 /** 35 * The function used to determine whether a key event should be ignored by React 36 * Hotkeys. By default, keyboard events originating elements with a tag name in 37 * ignoreTags, or a isContentEditable property of true, are ignored. 38 * 39 * @type {Function<KeyboardEvent>} 40 */ 41 ignoreEventsCondition: function, 42 43 /** 44 * Whether to ignore changes to keyMap and handlers props by default 45 * (this reduces a significant amount of unnecessarily resetting 46 * internal state) 47 * @type {boolean} 48 */ 49 ignoreKeymapAndHandlerChangesByDefault: true, 50 51 /** 52 * Whether to ignore repeated keyboard events when a key is being held down 53 * @type {boolean} 54 */ 55 ignoreRepeatedEventsWhenKeyHeldDown: true, 56 57 /** 58 * Whether React HotKeys should simulate keypress events for the keys that do not 59 * natively emit them. 60 * @type {boolean} 61 */ 62 simulateMissingKeyPressEvents: true, 63 64 /** 65 * Whether to call stopPropagation() on events after they are 66 * handled (preventing the event from bubbling up any further, both within 67 * React Hotkeys and any other event listeners bound in React). 68 * 69 * This does not affect the behaviour of React Hotkeys, but rather what 70 * happens to the event once React Hotkeys is done with it (whether it's 71 * allowed to propagate any further through the Render tree). 72 */ 73 stopEventPropagationAfterHandling: true, 74 75 /** 76 * Whether to call stopPropagation() on events after they are 77 * ignored (preventing the event from bubbling up any further, both within 78 * React Hotkeys and any other event listeners bound in React). 79 * 80 * This does not affect the behaviour of React Hotkeys, but rather what 81 * happens to the event once React Hotkeys is done with it (whether it's 82 * allowed to propagate any further through the Render tree). 83 */ 84 stopEventPropagationAfterIgnoring: true, 85 86 /** 87 * Whether to allow combination submatches - e.g. if there is an action 88 * bound to cmd, pressing shift+cmd will *not* trigger that action when 89 * allowCombinationSubmatches is false. 90 */ 91 allowCombinationSubmatches: false, 92 93 /** 94 * A mapping of custom key codes to key names that you can then use in your 95 * key sequences 96 */ 97 customKeyCodes: {}, 98});
react-hotkeys
provides comprehensive logging of all of its internal behaviour and allows setting one of 6 log levels.
The default level is warn
, which provides warnings and errors only, and is generally sufficient for most usage. However, if you are troubleshooting an issue or reporting a bug, you should increase the log level to debug
or verbose
to see what is going on, and be able to communicate it concisely.
You can set the logging level using the logLevel
configuration option.
For performance reasons, only some of the log levels are available in the production build. You will need to use the development build to get the full log output.
Log Level | Severity | Description | Available in Dev | Available in Prod |
---|---|---|---|---|
verbose | (highest) | debug + internal data representations | Yes | No |
debug | info + event propagation info | Yes | No | |
info | warn + general info | Yes | No | |
warn | (default) | error + warnings | Yes | Yes |
error | Errors only (ignore warnings) | Yes | Yes | |
none | (lowest) | Log nothing | Yes | Yes |
Logs appear in the developer console of the browser.
Each line is prefixed with (where applicable):
Each id is also given a coloured emoticon, to make it easy to visually trace the propagation of particular events through multiple components.
react-hotkeys
uses a lot of optimizations to help keep it as performant as possible (both in terms of time and memory). It can be helpful to be aware of some of these measures if you are seeing unexpected behaviour:
stopPropagation()
is called on all key events once react-hotkeys
has handled them. This can be disabled via the stopEventPropagationAfterHandling
and stopEventPropagationAfterIgnoring
configuration options.react-hotkeys
stops there (and does not build the full application's mappings of key sequences and handlers)react-hotkeys
doesn't do the work of finding its corresponding handler.document
when a global hotkey is defined (and are removed when the last one is unmounted).HTML5 allows any element with a tabindex
attribute to receive focus.
If you wish to support HTML4 you are limited to the following focusable elements:
<a>
<area>
<button>
<input>
<object>
<select>
<textarea>
If no elements have a tabindex
in a HTML document, the browser will tab between focusable elements in the order that they appear in the DOM.
If there are elements with tabindex
values greater than zero, they are iterated over first, according their tabindex
value (from smallest to largest). Then the browser tabs over the focusable elements with a 0
or unspecified tabindex
in the order that they appear in the DOM.
If any element is given a negative tabindex
, it will be skipped when a user tabs through the document. However, a user may still click or touch on that element and it can be focused programmatically (see below).
By default,
<HotKeys>
render its children inside an element with atabindex
of-1
. You can change this by passing atabIndex
prop to<HotKeys>
or you can change the defaulttabindex
value for allcomponents using the
defaultTabIndex` option for the Configuration API.
HTML5 supports a boolean autofocus
attribute on the following input elements:
<button>
<input>
<select>
<textarea>
It can be used to automatically focus parts of your React application, without the need to programmatically manage focus.
Only one element in the document should have this attribute at any one time (the last element to mount with the attribute will take effect).
To programmatically focus a DOM element, it must meet two requirements:
You can get a reference to an element using React's ref
property:
1class MyComponent extends Component { 2 componentDidUpdate(prevProps) { 3 if (!prevProps.isFocused && this.props.isFocused) { 4 this._container.focus(); 5 } 6 } 7 8 render() { 9 return <div ref={c => (this._container = c)}>My focusable content</div>; 10 } 11}
To get a reference to the DOM-mountable node used as a wrapper by <HotKeys />
, use the innerRef
prop:
1class MyComponent extends Component { 2 componentDidMount() { 3 this._container.focus(); 4 } 5 6 render() { 7 return ( 8 <HotKeys innerRef={ (c) => this._container = c } > 9 My focusable content 10 </div> 11 ) 12 } 13 14}
You can retrieve the element that is currently focused using the following:
1document.activeElement;
If you find that you want to bind to a key sequence that is already used by the browser, you can prevent the default behaviour by calling the preventDefault
method on the event object:
1event.preventDefault();
It's generally not advised to do this, as it likely violates the Principle of Least Surprise.
You have 3 options:
component
prop to specify a span
or some other alternative DOM-mountable component to wrap your component in, each time you render a component you don't want to wrap in a div element.defaultComponent
configuration option to specify a span
or some other alternative DOM-mountable component to wrap all <HotKeys>
children in.For improved performance, by default react-hotkeys
calls stopPropagation()
on all events that it handles. You can change this using the stopEventPropagationAfterHandling
and stopEventPropagationAfterIgnoring
configuration options.
Check that you are correctly passing the hotKeys props to a DOM-mountable component.
Make sure you are focusing a descendant of the <HotKeys>
component before you press the keys.
Check that the <HotKeys>
component that defines the handler is also an ancestor of the focused component, and is above (or is) the component that defines the handlers
.
Also make sure your React application is not calling stopPropagation()
on the key events before they reach the <HotKeys>
component that defines the keyMap
.
Finally, make sure your key event are not coming from one of the tags ignored by react-hotkeys.
This can happen when you have an action handler that either unmounts the <HotKeys>
component, or focuses an area of the application where there is no ancestor <HotKeys>
. The solution is to add a <HotKeys>
component with the root
prop to the top of your application - or at least high enough to not be unmounted or unfocused by your action handler.
1<HotKeys root> 2 // The parts of your application that are re-rendered or unfocused here 3</HotKeys>
Alternatively, you can add a <GlobalHotKeys/>
component anywhere in your application and it will close key combinations left hanging by your <HotKeys />
components due to missed keypress
and keyup
events.
react-hotkeys
adds a <div />
around its children with a tabindex="-1"
to allow them to be programmatically focused. This can result in browsers rendering a blue outline around them to visually indicate that they are the elements in the document that is currently in focus.
This can be disabled using CSS similar to the following:
1div[tabindex="-1"]:focus { 2 outline: 0; 3}
Please use Gitter to ask any questions you may have regarding how to use react-hotkeys
.
If you believe you have found a bug or have a feature request, please open an issue.
react-hotkeys
is considered stable and already being widely used (most notably Lystable and Whatsapp).
If you're interested in helping out with the maintenance of react-hotkeys
, make yourself known on Gitter, open an issue or create a pull request.
All contributions are welcome and greatly appreciated - from contributors of all levels of experience.
Collaboration is loosely being coordinated across Gitter and Projects.
This repository uses the meaningful emoji commits convention to help atomise and label commits.
react-hotkeys
uses a mixture of build tools to create each of the development and production bundles, which can be confusing to navigate and understand.
All build commands are included in the package.json
:
Command | Description |
---|---|
yarn prepublish | Build all bundles using babel and rollup |
yarn build-cjs | Build the development and production CommonJS bundles using babel and rollup, respectively |
yarn build-es | Build the development and production ES6 bundles using babel and rollup, respectively |
yarn build-umd | Build the development and production UMD bundles using rollup |
yarn build-development | Build the development CommonJS bundle using babel |
yarn build-es-development | Build the development ES6 bundle using babel |
yarn build-umd-development | Build the development ES6 bundle using rollup |
yarn build-production | Build the production CommonJS bundle using rollup |
yarn build-es-production | Build the production ES6 bundle using rollup |
yarn build-umd-production | Build the production ES6 bundle using rollup |
Bundle | Transpiled with | Modularized with | Output |
---|---|---|---|
CommonJS | Babel | Babel | /cjs/index.js |
UMD | Babel | Rollup | /umd/index.js |
ES6 | Babel | Babel | /es/index.js |
Bundle | Transpiled with | Optimized with | Minified with | Output |
---|---|---|---|---|
CommonJS | Babel | Rollup | Uglify | cjs/react-hotkeys.production.min.js |
UMD | Babel | Rollup | Uglify | /umd/react-hotkeys.min.js |
ES6 | Babel | Rollup | Babel-minify | /es/react-hotkeys.production.min.js |
To understand the configuration for any one build, you need to consult 3 places:
scripts
of package.json
.babelrc
file (match the env to the BABEL_ENV
value set in scripts
above)rollup.configs.js
(if applicable)All credit, and many thanks, goes to Chris Pearce for the inception of react-hotkeys
and all versions before 1.0.0
.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 5/25 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
108 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More