Skip to main content
/
/
/
useHotkey()

useHotkey()

import useHotkey from "@intility/bifrost-react/hooks/useHotkey";

Basic usage

Listen to platform-independent hotkeys.

  • key (string) - the key to listen to, like "k", "Escape", "ArrowUp" or " " (space). Maps to KeyboardEvent.key
  • callback (function) - will be called when user presses ⌘ + key on macOS, or Ctrl + key on win/linux
  • options (optional object) customize modifier keys and behavior. See options section below
  • returns an object with the hotkey ready to display, in two forms:
    • hotkeyJsx (ReactNode) renders one <kbd> per key, separated by +. Also see keyboard styling
    • hotkeyText (string) is the same hotkey as plain text, like "⌘ + K" or "Ctrl + K" depending on platform. Use this where markup is not possible, like an input placeholder
TSX
// listen to Ctrl/⌘ + K keypress
const { hotkeyJsx, hotkeyText } = useHotkey("k", (e) => {
  // focus search input, for example
  inputRef.current?.focus();
});

// hotkeyJsx will be: <kbd>Ctrl</kbd> + <kbd>K</kbd>
// or: <kbd>⌘</kbd> + <kbd>K</kbd>
<p>Press {hotkeyJsx} to search</p>

// hotkeyText will be a string: "Ctrl + K" or "⌘ + K"
<input placeholder={`Search (${hotkeyText})`} ref={inputRef} />

// arrow keys work too (assumes a moveUp function exists)
const { hotkeyJsx } = useHotkey("ArrowUp", moveUp);
// renders <kbd>Ctrl</kbd> + <kbd>↑</kbd>
// or <kbd>⌘</kbd> + <kbd>↑</kbd>

Options

For more control, pass a config object as the third parameter.

  • ctrlOrCmd (default true) listens to Ctrl on Windows/Linux or ⌘ (Command) on MacOS
  • shift (default false) listens to Shift (⇧) on all platforms
  • alt (default false) listens to Alt (⌥) on all platforms
  • preventDefault (default true) makes sure the keypress doesn't also trigger default behavior for browser, like typing in an input or another matching browser hotkey
TSX
// include Shift key
const { hotkeyJsx } = useHotkey("s", saveAll, {
  shift: true,
});
// renders Ctrl + Shift + S or ⌘ + ⇧ + S

// just Escape key (no modifiers)
const { hotkeyJsx } = useHotkey("Escape", closePopup, { ctrlOrCmd: false });
// renders Esc

// Listen to "e" keypress (no modifiers) but allow focused input to also receive the keypress
const { hotkeyJsx } = useHotkey("e", callbackFn, {
  ctrlOrCmd: false,
  preventDefault: false,
});
// renders E

Sandbox

Press the hotkeys to toggle the switch or focus the input.