useKeyboard

Accepts a reference to a component and attaches an event listener to it (attaches to document by default). Adds/removes the events on mount and unmount, and emits callback functions.

Import

import { useKeyboard } from '@contentful/f36-utils';

Examples

Basic example

By passing ref of Stack element to useKeyboard hook, you create event listeners, listed in keys prop. When focus is inside the Stack element, and one of the listed keyboard actions is triggered, the callback is called. In this example, it's function handleEvent.

Props (API reference)

Name

Type

Default

keys
required
{ [key: string]: (e: KeyboardEvent) => void; }

Object of key names and handlers defines which key to look for i.e. `ArrowUp`, `Escape`, `Shift` value is a callback function to be called when key matches

event
"keyup"
"keypress"
"keydown"

Defines the attached event type

'keydown'

Accessibility

This hook allows to implement keyboard accessibility according to many different requirements. To see most common interactions, check MDN Web Docs.

Help improve this page