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, a single lowercase character (like"k"or"s")callback(function) - will be called when user presses⌘ + keyon macOS, orCtrl + keyon win/linux- returns an object with
hotkeyText(string) which will be"⌘ + key"or"Ctrl + key"depending on platform
TSX
// listen to Ctrl/⌘ + K keypress
const { hotkeyText } = useHotkey("k", (e) => {
// focus search input, for example
inputRef.current?.focus();
});
// hotkeyText will be "Ctrl + K" or "⌘ + K"
// arrow keys work too (assumes a moveUp function exists)
const { hotkeyText } = useHotkey("ArrowUp", moveUp);
// hotkeyText will be "Ctrl + ↑" or "⌘ + ↑"Options
For more control, pass a config object as the third parameter.
ctrlOrCmd(defaulttrue) listens toCtrlon Windows/Linux or⌘(Command) on MacOSshift(defaultfalse) listens toShift(⇧) on all platformsalt(defaultfalse) listens toAlt(⌥) 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 { hotkeyText } = useHotkey("s", saveAll, {
shift: true,
});
// hotkeyText will be "Ctrl + Shift + S" or "⌘ + ⇧ + S"
// just Escape key (no modifiers)
const { hotkeyText } = useHotkey("Escape", closePopup, { ctrlOrCmd: false });
// hotkeyText will be "Esc"
// Listen to "e" keypress (no modifiers) but allow focused input to also receive the keypress
const { hotkeyText } = useHotkey("e", callbackFn, {
ctrlOrCmd: false,
preventDefault: false,
});
// hotkeyText will be "E"Sandbox
Move focus to the sandbox iframe (click inside) before testing hotkeys.
import useHotkey from "@intility/bifrost-react/hooks/useHotkey"; import Switch from "@intility/bifrost-react/Switch"; import { useState } from "react"; export default function HotkeyDemo() { const [on, setOn] = useState(false); const toggle = () => setOn(!on); const { hotkeyText } = useHotkey("s", toggle); return ( <Switch label={`press ${hotkeyText} to toggle`} checked={on} onChange={() => {}} /> ); }