useKeyPress
Detects keyboard key presses with optional callback support.
Import
Section titled “Import”import { useKeyPress, useKeyPressCallback } from 'asterui'State-based
Section titled “State-based”function KeyPressExample() { const escapePressed = useKeyPress('Escape')
useEffect(() => { if (escapePressed) closeModal() }, [escapePressed])
return <div>{escapePressed ? 'Escape pressed!' : 'Press Escape'}</div>}Callback-based
Section titled “Callback-based”function CallbackExample() { useKeyPressCallback('Escape', () => closeModal()) useKeyPressCallback('Enter', () => submitForm(), { preventDefault: true })
return <Form>...</Form>}Parameters
Section titled “Parameters”useKeyPress
Section titled “useKeyPress”| Parameter | Type | Description |
|---|---|---|
targetKey | string | Key to detect (e.g., 'Enter', 'Escape', 'a') |
options | UseKeyPressOptions | Configuration options |
useKeyPressCallback
Section titled “useKeyPressCallback”| Parameter | Type | Description |
|---|---|---|
targetKey | string | Key to detect |
callback | (event: KeyboardEvent) => void | Function to call |
options | UseKeyPressOptions | Configuration options |
Options
Section titled “Options”| Property | Type | Default | Description |
|---|---|---|---|
target | HTMLElement | Window | window | Target element for listener |
event | 'keydown' | 'keyup' | 'keydown' | Event type to listen for |
preventDefault | boolean | false | Prevent default browser behavior |
Return Value (useKeyPress)
Section titled “Return Value (useKeyPress)”| Type | Description |
|---|---|
boolean | True while the key is pressed |