|Kit

useHotkey

Binds a keyboard shortcut, and says where it applies — anywhere, outside or only inside text fields, inside an element, under the pointer — while yielding to overlays opened above it.

useHotkey calls a handler when a keyboard shortcut is pressed. It's the hook behind Spotlight's ⌘K.

import { useHotkey } from '@42-central/ui-react';

useHotkey('mod+s', () => save());
useHotkey(['j', 'arrowdown'], next, { scope: list, repeat: true });

The matched event's default is prevented, so the browser's own shortcut on the same keys (⌘S's Save dialog) doesn't also run. Pass false instead of a key to bind nothing, e.g. while a feature is off.

Matching

A hotkey is modifiers and a key joined with +, the key last: "mod+k", "shift+mod+p", "alt+/".

  • mod is ⌘ on Apple platforms and Ctrl elsewhere, the usual convention for app shortcuts. meta (cmd, command), ctrl (control), alt (option) and shift name one key explicitly.
  • Modifiers match exactly. mod+k doesn't fire on ⌘⇧K, and k doesn't fire on ⌘K.
  • The key follows the keyboard layout. It's compared case-insensitively with event.key, so "mod+z" is the key that types z on an AZERTY keyboard too. Name special keys as event.key does: enter, escape, arrowdown, backspace, delete, tab; the space bar is space and the plus key is a trailing + ("mod++").
  • A modifier can be the key: "alt" fires when ⌥ itself is pressed (or released, with event: "keyup").
  • IME composition is ignored, so confirming a Japanese or Chinese candidate with ↵ doesn't fire an enter hotkey.
  • A misspelled modifier binds nothing. "ctl+k" matches no key at all, rather than firing on a bare k, and warns in development.

When it fires

By default a hotkey fires anywhere on the page, unless an overlay is open above the component that bound it, the key is an auto-repeat, or a component already handled the event. In a text field, a ⌘/Ctrl/Alt hotkey fires too, and a bare-key one (/, ?, j) doesn't, so typing it types the character. The options below narrow or widen that.

Anywhere

The default for a ⌘/Ctrl/Alt hotkey, an app-wide command like ⌘K or ⌘S. It also fires while typing, since such a shortcut can't type a character. inputs: "allow" (or true) gives a bare key the same reach.

Press CtrlJ anywhere on the page, in the field too.

Pressed: 0

Code

const [count, setCount] = useState(0);
useHotkey('mod+j', () => setCount((value) => value + 1));

<Kbd hotkey="mod+j" />
<TextInput aria-label="Any field" placeholder="Focus me, then press it" />
<p>Pressed: {count}</p>

Outside text fields

inputs: "ignore" (or false) keeps a hotkey out of text fields. It's already the default for a bare key or a shift+ one: a / or ? would otherwise swallow the character being typed (WCAG 2.1.4). A text field is a text <input>, a <textarea> or a contenteditable. Buttons, checkboxes, sliders and selects are not text fields: to yield to those, use when.

Press / to focus the search. Inside it, the key types a slash.

Code

const search = useRef<HTMLInputElement>(null);
useHotkey('/', () => search.current?.focus(), { inputs: 'ignore' });

<TextInput ref={search} aria-label="Search" placeholder="Search…" />

Only in text fields

inputs: "only" is the reverse: ⌘↵ to send a comment, Esc to clear a search box. Add a scope so it fires only in that field.

Write a comment and press CtrlEnter to send it.

Sent: nothing yet

Code

const field = useRef<HTMLTextAreaElement>(null);
useHotkey('mod+enter', send, { inputs: 'only', scope: field });

<Textarea ref={field} aria-label="Comment" placeholder="Write a comment…" />

Inside an element

scope takes a ref: the hotkey fires only while focus is inside that element, like ⌘A selecting a table's rows rather than the page. A scope that is inert or hidden, itself or through an ancestor (a closed Collapse, an inactive Tabs panel), counts as outside.

This demo also passes repeat: true: holding J keeps moving down. Auto-repeat is off by default, since a held key toggling or deleting something thirty times a second is the costly surprise; a skipped repeat still has its default prevented.

Click into the list, then J / K (hold to keep going). Outside it, they do nothing.

Inbox
Drafts
Sent
Archive
Spam
Trash

Code

const list = useRef<HTMLDivElement>(null);
useHotkey(['j', 'arrowdown'], () => move(1), { scope: list, repeat: true });
useHotkey(['k', 'arrowup'], () => move(-1), { scope: list, repeat: true });

<div ref={list} role="listbox" tabIndex={0}>…</div>

Under the pointer

With hover, the pointer resting on the scope counts as being inside it, no focus needed: hover a row, press a key to act on that row.

Rest the pointer on a row and press E to archive it.

  • Fix the login redirectE
  • Translate the footerE
  • Bump the date libraryE

Code

function Row({ title, onArchive }) {
  const row = useRef<HTMLLIElement>(null);
  useHotkey('e', onArchive, { scope: row, hover: true });

  return <li ref={row}>{title} <Kbd hotkey="e" /></li>;
}

Not under an overlay

layer is on by default: a hotkey goes quiet while a Modal, Drawer, Popover or a picker's list is open above the component that bound it. A page's j stops counting while the modal is open; the modal's own j takes over, and goes quiet in turn while a nested modal is open above it.

It's read from React context, not the DOM, so it follows the component tree through portals: what counts is what opened from the component's layer. A hotkey that must also reach the overlay it opened (a toggle like Spotlight's ⌘K) passes layer: false.

Press J, then open the modal and press it again.

Page presses: 0

Code

function Page() {
  const [open, setOpen] = useState(false);
  useHotkey('j', countOnThePage); // quiet while the modal is open

  return (
    <Modal open={open} onOpenChange={setOpen} title="Layered hotkeys">
      <ModalCounter /> {/* its own useHotkey('j', …) fires */}
    </Modal>
  );
}

Hold and release

event: "keyup" fires on release. Pair it with a keydown hotkey on the same key for hold-to-peek or push-to-talk.

Hold Alt to see the shortcuts, release to hide them.

Code

const [peeking, setPeeking] = useState(false);
useHotkey('alt', () => setPeeking(true));
useHotkey('alt', () => setPeeking(false), { event: 'keyup' });

<Button>New issue {peeking && <Kbd hotkey="c" />}</Button>

Native controls

when has the last word on a matched event, after every other option. Its default skips an event a component already handled (event.defaultPrevented: Select's ↵, a dialog's Esc). A when of your own replaces that default, so keep the check unless the hotkey should run even then:

// Leave Space to a focused button or checkbox.
useHotkey('space', togglePlay, {
  when: (event) =>
    !event.defaultPrevented &&
    !(event.target instanceof Element && event.target.closest('button, [role="checkbox"]')),
});

// Also fire on events a component already handled.
useHotkey('escape', closePanel, { when: () => true });

Labels

hotkeyKeys lists a hotkey's keys the way the platform writes them, one label per key cap: "mod+k" is ["⌘", "K"] on Apple platforms and ["Ctrl", "K"] elsewhere. Modifiers come in Apple's order (⌃⌥⇧⌘) whatever order the string names them in. formatHotkey joins that list into one string for plain-text places, a title or a tooltip: ⌘K / Ctrl K, ⇧⌘P / Ctrl Shift P.

import { formatHotkey, hotkeyKeys } from '@42-central/ui-react';

hotkeyKeys('mod+shift+p', true); // ["⇧", "⌘", "P"]
hotkeyKeys('mod+shift+p', false); // ["Ctrl", "Shift", "P"]
formatHotkey('mod+shift+p', true); // "⇧⌘P"
formatHotkey('mod+shift+p', false); // "Ctrl Shift P"

Both take Kbd's translations as an optional third argument, merged per key onto the English words, so a tooltip and the caps beside it read the same:

const german = { ctrl: 'Strg', del: 'Entf' };

formatHotkey('mod+shift+delete', false, german); // "Strg Shift Entf"
formatHotkey('mod+shift+delete', true, german); // "⇧⌘⌦": Apple's glyphs aren't words
<Kbd hotkey="mod+shift+delete" translations={german} />;

The platform defaults to the visitor's, which a server can't know. While rendering, pass useApplePlatform() (false on the server and during hydration, the real answer right after) so the server markup and the first client render agree. On screen, let Kbd do it: <Kbd hotkey="mod+k" /> draws one cap per key, with an icon for each key that has one.

matchHotkey(hotkey, event) is the matcher on its own, for a handler you attach yourself:

import { matchHotkey } from '@42-central/ui-react';

<input onKeyDown={(event) => matchHotkey('mod+enter', event) && submit()} />;

API

Parameters

Prop

Type

Options

Prop

Type

Helpers

Prop

Type

On this page