Hooks
/ API Reference
Hooks
/ 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/hooks'

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.
On this page