Hook
/ API Reference
Hook
/ API Reference

useKeyDown

A hook that calls a callback when a key is pressed.
By default, the hook listens for the key press on the document element.

Tip

Use active if multiple components with the same hook are mounted. Then only the ones with active will trigger. No need to stop popagation in this case.

The Gist

'use client'
import { useKeyDown } from '@weser/hook'

function Component() {
  useKeyDown('Enter', () => console.log('Enter key pressed'))

  return <div>Press Enter to log</div>
}

Parameters

ParameterTypeDescription
keyCodestringThe key code to listen for.
callback() => voidThe callback to call when the key is pressed.
optionsOptions?The options for the hook.

Options

ParameterTypeDefaultDescription
targetRefObject?documentThe target to listen for the key press.
activeboolean?trueWhether the hook is active.
modifiersModifiers?{}The modifier keys that must be pressed.

Modifiers

ParameterTypeDefaultDescription
ctrlboolean?falseWhether the Ctrl key must be pressed.
metaboolean?falseWhether the Meta (Cmd on Mac) key must be pressed.
altboolean?falseWhether the Alt key must be pressed.
shiftboolean?falseWhether the Shift key must be pressed.
On this page