Skip to content

🅰 A React hook for handling `keydown` events on specific `event.key` values. It also normalizes non-standard `event.key` values from IE to their modern equivalents.

License

Notifications You must be signed in to change notification settings

accessible-ui/use-key

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


useKey()

Bundlephobia Code coverage Build status NPM Version MIT License

npm i @accessible/use-key

A React hook for handling keydown events on specific event.key values. It also normalizes non-standard event.key values from IE to their modern equivalents.

Quick Start

import * as React from 'react'
import useKey from '@accessible/use-key'

const Component = () => {
  const ref = React.useRef(null)

  // Listens to keydown events on the `ref` above
  useKey(ref, {
    // Logs event when the Escape key is pressed
    Escape: console.log,
    // Logs "Key was pressed: Enter" to the console when Enter is pressed
    Enter: (event) => console.log('Key was pressed:', event.key),
  })

  // Listens to keydown events on the window
  useKey(window, {
    // Logs event when the Escape key is pressed
    Escape: console.log,
    // Logs "Key was pressed: Enter" to the console when Enter is pressed
    Enter: (event) => console.log('Key was pressed:', event.key),
  })

  return <div ref={ref} />
}

API

useKey(target, handlers)

Arguments

Argument Type Required? Description
target React.RefObject<T> | T | Window | Document | null Yes A React ref, element, window, or document to add the key listener to
handlers Record<string, (event?: KeyboardEvent) => any> Yes A mapping with keys matching the event.key string you want to listen on. The value for each key should be an event listener.

Returns void

LICENSE

MIT

About

🅰 A React hook for handling `keydown` events on specific `event.key` values. It also normalizes non-standard `event.key` values from IE to their modern equivalents.

Resources

License

Stars

Watchers

Forks

Packages

No packages published