useHotkey
function useHotkey(
keys: string,
handler: (event: KeyboardEvent) => void,
options?: HotkeyOptions,
): void;
interface HotkeyOptions {
enabled?: boolean; // defaults to true
ignoreInputs?: boolean; // defaults to true
}
Calls handler when a keyboard shortcut is pressed anywhere on the page.
keysis a key name, optionally after modifiers joined with+:"Escape","/","ctrl+s","mod+shift+k". Key names areKeyboardEvent.keyvalues, in any case.- Modifiers are
ctrl,alt,shift,metaandmod, which means ⌘ on Apple platforms and Ctrl elsewhere. They must match exactly:"ctrl+s"doesn't fire for Ctrl+Shift+S. - For symbols such as
"?", Shift isn't checked unless you list it, because keyboard layouts differ in which symbols need it. Usespaceandplus(or"ctrl++") for those keys. - Presses while typing in an input, textarea, select or editable content are ignored, unless
ignoreInputsisfalse. - An invalid shortcut such as
"ctrl+"or"hyper+k"never fires. - The handler can call
event.preventDefault()to stop the browser's own shortcut.
Live demo
Click here, then press ?
Example
import { useState } from "react";
import { useHotkey } from "react-honey-hooks";
function Editor({ save }: { save: () => void }) {
const [paletteOpen, setPaletteOpen] = useState(false);
useHotkey("mod+s", (event) => {
event.preventDefault(); // don't open the browser's "Save page" dialog
save();
});
useHotkey("mod+k", () => {
setPaletteOpen(true);
});
useHotkey(
"Escape",
() => {
setPaletteOpen(false);
},
{ enabled: paletteOpen, ignoreInputs: false },
);
return paletteOpen ? <CommandPalette /> : <Document />;
}