useKeyboard
Subscribes to keyboard events with a map of key → handler. Keys are matched against event.key (case-insensitive). Pass a tuple to require specific modifier keys, and to opt into preventDefault / stopPropagation.
By default the listener is attached to window, but you can pin it to a specific element via the target option.
import { useRef } from 'react'
import { useKeyboard } from '@wire-ui/react'
function CommandPalette({ onSave, onClose }: { onSave: () => void; onClose: () => void }) {
const inputRef = useRef<HTMLInputElement>(null)
useKeyboard({
Escape: onClose,
s: [onSave, { meta: true, preventDefault: true }],
Enter: [() => console.log('submit'), { preventDefault: true }],
}, {
target: inputRef,
event: 'keydown',
})
return <input ref={inputRef} placeholder="⌘S to save, Esc to close" />
}Parameters
| Param | Type | Description |
|---|---|---|
map | KeyboardMap | Object of key → handler or key → [handler, options]. |
options | UseKeyboardOptions | See below. |
KeyboardMap
type KeyHandler = (event: KeyboardEvent) => void
interface KeyboardHandlerOptions {
ctrl?: boolean
meta?: boolean
shift?: boolean
alt?: boolean
preventDefault?: boolean
stopPropagation?: boolean
}
type KeyboardMap = Record<string, KeyHandler | [KeyHandler, KeyboardHandlerOptions]>Modifier flags use exact match — { meta: true } only fires when Meta is held and won’t match plain key presses. Omit a modifier to ignore its state.
Options
| Option | Type | Default | Description |
|---|---|---|---|
target | RefObject<HTMLElement | null> | HTMLElement | Window | Document | null | window | Element to attach the listener to. |
event | 'keydown' | 'keyup' | 'keypress' | 'keydown' | Which keyboard event to listen on. |
enabled | boolean | true | Toggle the listener without unmounting. |
Last updated on