useHotkey()
import useHotkey from "@intility/bifrost-react/hooks/useHotkey";useHotkey()
Go to top
Basic usage
Listen to platform-independent hotkeys.
key(string) - the key to listen to, like"k","Escape","ArrowUp"or" "(space). Maps toKeyboardEvent.keycallback(function) - will be called when user presses ⌘ +keyon macOS, or Ctrl +keyon win/linuxoptions(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 stylinghotkeyText(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 inputplaceholder
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(defaulttrue) listens to Ctrl on Windows/Linux or ⌘ (Command) on MacOSshift(defaultfalse) listens to Shift (⇧) on all platformsalt(defaultfalse) listens to Alt (⌥) on all platformspreventDefault(defaulttrue) 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 ESandbox
Press the hotkeys to toggle the switch or focus the input.