@blueprintjs/core
Version:
Core styles & components
84 lines (62 loc) • 3.1 kB
Markdown
---
tag: new
---
@
<div class="@ns-callout @ns-intent-primary @ns-icon-info-sign">
<h5 class="@ns-heading">
Migrating from [HotkeysTarget](
</h5>
`useHotkeys` is a replacement for HotkeysTarget. You are encouraged to use this new API in your function
components, or the [HotkeysTarget2 component](
as they will become the standard APIs in a future major version of Blueprint. See the full
[](https://github.com/palantir/blueprint/wiki/HotkeysTarget-&-useHotkeys-migration) on the wiki.
</div>
The `useHotkeys` hook adds hotkey / keyboard shortcut interactions to your application using a custom React hook.
Compared to the deprecated [Hotkeys](
corresponding [context provider](
Focus on the piano below to try its hotkeys. The global hotkeys dialog can be shown using the "?" key.
@reactExample UseHotkeysExample
@
First, make sure [HotkeysProvider](
React application.
Then, to register hotkeys and generate the relevant event handlers, use the hook like so:
```tsx
import { InputGroup, KeyCombo, useHotkeys } from "@blueprintjs/core";
import React, { createRef, useCallback, useMemo } from "react";
export default function() {
const inputRef = createRef<HTMLInputElement>();
const handleRefresh = useCallback(() => console.info("Refreshing data..."), []);
const handleFocus = useCallback(() => inputRef.current?.focus(), [inputRef]);
// important: hotkeys array must be memoized to avoid infinitely re-binding hotkeys
const hotkeys = useMemo(() => [
{
combo: "R",
global: true,
label: "Refresh data",
onKeyDown: handleRefresh,
},
{
combo: "F",
group: "Input",
label: "Focus text input",
onKeyDown: handleFocus,
},
], [handleRefresh, handleFocus]);
const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeys);
return (
<div tabIndex={0} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}>
Press <KeyCombo combo="R" /> to refresh data, <KeyCombo combo="F" /> to focus the input...
<InputGroup inputRef={inputRef} />
</div>
);
}
```
__Important__: the `hotkeys` array must be memoized, as shown above, to prevent the hook from re-binding
hotkeys on every render.
Hotkeys must define a group, or be marked as global. The hook will automatically bind global event handlers
and configure the <kbd>?</kbd> key to open the generated hotkeys dialog, but it is up to you to bind _local_
event handlers with the returned `handleKeyDown` and `handleKeyUp` functions. The hook takes an optional
second parameter which can customize some of its default behavior.
@interface UseHotkeysOptions
@method useHotkeys
@interface HotkeyConfig