raddix

useKeyboard

Allows listening and handling keyboard events.

Features

  • It supports key checking, using under the hood the event.key property and if you need to use other properties like event.code you can change it in the configuration using the checker option.
  • 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.

import { useKeyboard } from '@raddix/use-keyboard';
import { useState } from 'react';
export const Example = () => {
const [bgColor, setBgColor] = useState('');
const onkeyDown = useKeyboard(() => {
setBgColor('red');
});
const onkeyUp = useKeyboard(() => {
setBgColor('blue');
});
return (
<div>
<input
type='text'
onKeyDown={onkeyDown}
onKeyUp={onkeyUp}
style={{ background: bgColor }}
/>
</div>
);
};

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.

import { useState } from 'react';
import { useKeyboard } from '@raddix/use-keyboard';
export const Example = () => {
const [error, setError] = useState(false);
const onkeyDown = useKeyboard(() => {
setError(true);
}, ['á', 'é', 'í', 'ó', 'ú', 'ñ']);
return (
<div>
<label htmlFor='Username'>Username</label>
<input type='text' id='Username' onKeyDown={onkeyDown} />
<p>
{error
? 'Im sorry, but semigraphic characters are not supported'
: 'You can use letters, numbers and punctuation marks'}
</p>
</div>
);
};

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.

import { useKeyboard } from '@raddix/use-keyboard';
export const Example = () => {
useKeyboard(() => alert('Success'), ['c'], { globalEvent: true });
return (
<div>
Press <code>c</code>
</div>
);
};

API

Parameters

NameDescriptionRequiredType
handlerFunction that is called once the keys have been pressedYes(e:KeyboardEvent)=>void
shortcutList of keys for verificationNoArray<string | number>
optionsConfiguration optionsNoObject

Configuration Options

NameDescriptionRequiredDefault ValueType
globalEventEnable global events from the documentNofalseboolean
stopPropagationStop event PropagationNotrueboolean
preventDefaultBlock the default behavior of eventNofalseboolean
checkerProperty of the KeyboardEvent object to identify a keyNokey"key" | "code"