UseDetectKeyDown

Last updated: 2.0.0 (22/01/2024)

useDetectKeyDown detects when a key is pressed and fires the callback function. It attaches the event listener to the document body, thus making it handy for keyboard shortcuts, etc.

Usage

import { useDetectKeyDown, Text } from "@valence-ui/core";

function MyComponent() { 
    useDetectKeyDown(
        (e) => console.log("Key pressed!", e),
        "Escape",
        true,
    );
    
    return ( 
        <Text> 
            Press `Escape`!
        </Text>
    )
}

Listen for multiple keys

Passing a list of keycodes into the keys parameter allows the hook to listen for any number of keys. A switch block in the callback function may be necessary to distinguish between the keys pressed.

Controlled listening

Using a Disclosure or boolean state allows you to control when the hook is listening for keyboard events, without unmounting the component it is attached to.


Parameters

Parameter
Type
Description

callback (required)

(e: KeyboardEvent) => void

The function to call when the key is pressed.

keys (required)

string | string[]

A key or array of keys to listen for.

runCheck

boolean

Whether to listen for keyboard events.

deps

any[]

Any dependencies to pass to the useEffect hook.

Last updated

Was this helpful?