useKeyStroke

Tags:

A React Hook that helps to handle key strokes.

Demo

Try to (long) press -/= to increase/decrease the counter, - will ignore repeated events (set dedupe to true).

Source
Count:
0
↓ / -
↑ / =

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

// catch all key strokes
const stop = useKeyStroke(handler, options)

// catch specific key strokes
const stop = useKeyStroke(keyFilter, handler, options)

KeyFilter

For all keys for keyboard events see MDN.

export type KeyFilter = true | string | string[] | KeyPredicate

Handler

export type UseKeyStrokeHandler = (event: KeyboardEvent) => void

Options

ElementTarget is a union type that represents various kinds of elements that can be targeted.

See ElementTarget or ElementTarget Types for more details.

export type KeyStrokeEventName = 'keydown' | 'keypress' | 'keyup'

export type UseKeyStrokeOptions = {
  /**
   * The event name to listen for.
   *
   * @defaultValue 'keydown'
   */
  eventName?: KeyStrokeEventName
  /**
   * The target to add the event listener to.
   *
   * @defaultValue () => window
   */
  target?: ElementTarget | (() => Window) | (() => Document)
  /**
   * Set to `true` to use passive event listeners.
   *
   * @defaultValue false
   */
  passive?: boolean
  /**
   * Set to `true` to ignore repeated events when the key is being held down.
   *
   * @defaultValue false
   */
  dedupe?: boolean
}

Returns

A function that can be called to stop listening for key strokes.