useKeyboard

useKeyboard is a simple hook that accepts a reference to a component and attaches event listener to the component. By default attaches to document. Adds/remove 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

    keys(required)

    Description

    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

    { [key: string]: (e: KeyboardEvent) => void; }
  • Name

    event

    Description

    Defines the attached event type

    "keyup"
    "keypress"
    "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