useHotkeys
Listen for keyboard shortcuts.
Import
import { useHotkeys } from '@tidbcloud/uikit'Usage
useHotkeys accepts an array of hotkeys and handler tuples:
hotkey- hotkey string, for examplectrl+E,shift+alt+L,mod+Shandler- event handler called when the combination is pressedoptions- optional object with extra options
import { useHotkeys } from '@tidbcloud/uikit'
function Demo() {
useHotkeys([
['mod+J', () => console.log('Toggle color scheme')],
['ctrl+K', () => console.log('Trigger search')],
['alt+mod+shift+X', () => console.log('Special action')]
])
return <div>Press hotkeys to trigger actions</div>
}Ignored Elements
By default, hotkey events are ignored if focus is in input, textarea, and select elements. You can change this:
import { useHotkeys } from '@tidbcloud/uikit'
function Demo() {
// Ignore only when focus is in input and textarea
useHotkeys([['ctrl+K', () => console.log('Search')]], ['INPUT', 'TEXTAREA'])
// Do not ignore any element
useHotkeys([['ctrl+K', () => console.log('Search')]], [])
}Targeting Elements
For specific elements, use getHotkeyHandler:
import { useState } from 'react'
import { TextInput } from '@tidbcloud/uikit'
import { getHotkeyHandler } from '@tidbcloud/uikit'
function Demo() {
const [value, setValue] = useState('')
return (
<TextInput
placeholder="Press Enter to submit, Escape to clear"
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
onKeyDown={getHotkeyHandler([
['Enter', () => console.log('Submit:', value)],
['Escape', () => setValue('')]
])}
/>
)
}Supported Formats
mod+S– detects⌘+Son macOS andCtrl+Son Windowsctrl+shift+X– handles multiple modifiersalt + shift + L– whitespace is allowedArrowLeft– special keys using KeyboardEvent.key formatshift + [plus]– use[plus]to detect+key
Definition
interface HotkeyItemOptions {
preventDefault?: boolean
usePhysicalKeys?: boolean
}
type HotkeyItem = [string, (event: KeyboardEvent) => void, HotkeyItemOptions?]
function useHotkeys(hotkeys: HotkeyItem[], tagsToIgnore?: string[], triggerOnContentEditable?: boolean): void