Documentation
useKeyboard

useKeyboard

The useKeyboard hook is a powerful utility that allows you to handle keyboard events with specific key bindings in your React components. This hook supports a wide range of configurations, including handling modifier keys (like Ctrl, Cmd, Shift, and Alt), and provides options for controlling the behavior of the keyboard event, such as stopping propagation or preventing default actions.

Usage

First, you need to import the useKeyboard hook from the kitchn package.

import { useKeyboard } from "kitchn";

Example

Here is an example of how to use the useKeyboard hook in a component:

Parameters

The useKeyboard hook accepts the following parameter:

NameTypeDescription
handler(event: React.KeyboardEvent | KeyboardEvent) => voidThe function to execute when the specified key(s) are pressed.
keyBindingsnumber[] | numberThe key code(s) to bind. These can include key codes and modifier keys from the KeyMod enum.
optionsKeyboardOptions (optional)An object to configure the behavior of the event listener.

KeyboardOptions

NameTypeDefaultDescription
disableGlobalEventbooleanfalseIf true, the hook will not bind the event listener globally to the document.
stopPropagationbooleanfalseIf true, the event propagation will be stopped when the key is pressed.
preventDefaultbooleanfalseIf true, the default action for the event will be prevented.
capturebooleanfalseIf true, the event will be captured during the capture phase.
event"keydown" | "keypress" | "keyup""keydown"The type of keyboard event to listen for.

Return Value

The useKeyboard hook returns an object with the following properties:

PropertyTypeDescription
bindingsReact.HTMLProps<HTMLInputElement>An object containing event handlers (onKeyDown, onKeyUp, onKeyPress, etc.) that can be spread onto elements to bind the key events.