use-hotkey
v0.1.0
Published
React Hooks for keyboard shortcuts
Downloads
1
Readme
use-hotkey
EXPERIMENTAL: React Hooks for keyboard shortcuts
Install
npm install use-hotkey
Usage
import {
useHotkey,
useScopedHotkey,
useScopedHotkeyProvider,
useKeyBindings,
} from 'use-hotkey'
// add global shortcut
const SearchBar = () => {
const inputRef = useRef(null)
const focusInput = () => inputRef.current.focus()
useHotkey('/', focusInput)
return (
<div>
<input ref={inputRef} placeholder="Search" />
</div>
)
}
// add scoped shortcut
const LikeButton = () => {
// const toggleLike = useCallback(...)
useScopedHotkey('/', toggleLike)
return (
<Button onClick={toggleLike}>
Like
</Button>
)
}
// add context for scoped shortcut:
const TimelineItem = () => {
const nodeRef = useRef(null)
const ScopedHotkeyContextProvider = useScopedHotkeyContextProvider(nodeRef)
return (
<ScopedHotkeyContextProvider>
<li ref={nodeRef} />
{/* ... */}
<LikeButton />
</li>
</ScopedHotkeyContextProvider>
)
}
const KeyBindings = () => {
const keyBindings = useKeyBindings()
return (
<div>
<h2>Keyboard Shortcuts</h2>
<div css={{display: 'flex', flexWrap: 'wrap'}}>
{[...keyBindings].map(([scope, bindings]) => (
<div key={scope} css={{width: '50%'}}>
<h3 css={{textTransform: 'capitalize'}}>{scope}</h3>
<dl>
{[...bindings]
.sort(([keysA], [keysB]) => keysA.localeCompare(keysB))
.map(([keys, {name}]) =>
<React.Fragment key={keys}>
<dt>
<kbd>{keys}</kbd>
</dt>
<dd>{name}</dd>
</React.Fragment>
)}
</dl>
</div>
))}
</div>
</div>
)
}