useKeyboardShortcut
The useKeyboardShortcut hook calls a callback when a user presses a key with
the platform shortcut modifier: Command on macOS or Control on Windows and
Linux.
Import
import { useKeyboardShortcut } from "@cfa/react-core";Usage
Toggle A Panel
function Example() { const [isOpen, setIsOpen] = React.useState(false);
useKeyboardShortcut(() => { setIsOpen((open) => !open); }, "b");
return ( <div> <Button onPress={() => setIsOpen((open) => !open)}>Toggle panel</Button> {isOpen && <div>Panel content</div>} </div> );}Disable A Shortcut
Pass null as the callback when a shortcut should not be active.
function Example({ disabled }: { disabled: boolean }) { useKeyboardShortcut( disabled ? null : () => { console.log("Shortcut pressed"); }, "k" );
return <Button isDisabled={disabled}>Open command menu</Button>;}API
useKeyboardShortcut(callback: (() => void) | null, key: string): voidParameters
callback- Function called when the shortcut is pressed. Passnullto disable the shortcut without conditionally calling the hook.key- The key to pair with the platform shortcut modifier.
Behavior
- Listens for Command+key on macOS and Control+key on Windows/Linux.
- Calls
preventDefault()when the shortcut matches. - Ignores shortcuts while focus is in an input, textarea, or contenteditable element.