useKeyboard
Allows listening and handling keyboard events.
Features
- It supports key checking, using under the hood the
event.keyproperty and if you need to use other properties likeevent.codeyou can change it in the configuration using thecheckeroption. - Propagation is stopped by default if there is an event handler, so that a parent component does not respond to an event already handled by a child element.
Installation
Install the custom hook from your command line.
npm i @raddix/use-keyboard
Usage
Basic example
In this example pressing a key inside the text field sets a red background color and releasing the key sets a blue background color.
Key verification
This example shows an input element that does not allow semigraphic characters.
Add semigraphic characters to the useKeyboard Array so that it does the key checking when the onKeyDown event is executed.
Global keyboard events
In this example, we will raise an alert when the a key is pressed.
In order for the useKeyboard hook to detect global events we need to
set the globalEvent: true option.
API
Parameters
| Name | Description | Required | Type |
|---|---|---|---|
| handler | Function that is called once the keys have been pressed | Yes | (e:KeyboardEvent)=>void |
| shortcut | List of keys for verification | No | Array<string | number> |
| options | Configuration options | No | Object |
Configuration Options
| Name | Description | Required | Default Value | Type |
|---|---|---|---|---|
| globalEvent | Enable global events from the document | No | false | boolean |
| stopPropagation | Stop event Propagation | No | true | boolean |
| preventDefault | Block the default behavior of event | No | false | boolean |
| checker | Property of the KeyboardEvent object to identify a key | No | key | "key" | "code" |