Hook
/ API ReferenceHook
/ API ReferenceuseKeyDown
A hook that calls a callback when a key is pressed.
By default, the hook listens for the key press on the document element.
Tip
Use active if multiple components with the same hook are mounted. Then only
the ones with active will trigger. No need to stop popagation in this case.
The Gist
'use client'
import { useKeyDown } from '@weser/hook'
function Component() {
useKeyDown('Enter', () => console.log('Enter key pressed'))
return <div>Press Enter to log</div>
}
Parameters
| Parameter | Type | Description |
|---|---|---|
| keyCode | string | The key code to listen for. |
| callback | () => void | The callback to call when the key is pressed. |
| options | Options? | The options for the hook. |
Options
| Parameter | Type | Default | Description |
|---|---|---|---|
| target | RefObject? | document | The target to listen for the key press. |
| active | boolean? | true | Whether the hook is active. |
| modifiers | Modifiers? | {} | The modifier keys that must be pressed. |
Modifiers
| Parameter | Type | Default | Description |
|---|---|---|---|
| ctrl | boolean? | false | Whether the Ctrl key must be pressed. |
| meta | boolean? | false | Whether the Meta (Cmd on Mac) key must be pressed. |
| alt | boolean? | false | Whether the Alt key must be pressed. |
| shift | boolean? | false | Whether the Shift key must be pressed. |
© 2024-present Robin Weser. All Rights Reserved.