Medium
How to Create a Custom Keyboard Shortcut Hook in React with Event Handling
You need to implement a custom keyboard shortcut hook. What's missing?
1<p>function useKeyboardShortcut(shortcuts) {</p><p> const handleKeyPress = useCallback((event) => {</p><p> const { key, ctrlKey, shiftKey, altKey } = event;</p><p> </p><p> const shortcut = shortcuts.find(s => {</p><p> const keyMatch = s.key.toLowerCase() === key.toLowerCase();</p><p> const ctrlMatch = Boolean(s.ctrlKey) === ctrlKey;</p><p> const shiftMatch = Boolean(s.shiftKey) === shiftKey;</p><p> const altMatch = Boolean(s.altKey) === altKey;</p><p> </p><p> return keyMatch && ctrlMatch && shiftMatch && altMatch;</p><p> });</p><p> </p><p> if (shortcut) {</p><p> shortcut.action();</p><p> }</p><p> }, [shortcuts]);</p><p> </p><p> useEffect(() => {</p><p> document.addEventListener('keydown', handleKeyPress);</p><p> return () => document.removeEventListener('keydown', handleKeyPress);</p><p> }, [handleKeyPress]);</p><p>}</p><p>// Usage example</p><p>function Editor() {</p><p> const [content, setContent] = useState('');</p><p> const [isBold, setIsBold] = useState(false);</p><p> </p><p> useKeyboardShortcut([</p><p> {</p><p> key: 's',</p><p> ctrlKey: true,</p><p> action: () => saveContent(content)</p><p> },</p><p> {</p><p> key: 'b',</p><p> ctrlKey: true,</p><p> action: () => setIsBold(prev => !prev)</p><p> }</p><p> ]);</p><p> </p><p> return (</p><p> <div></p><p> <textarea</p><p> value={content}</p><p> onChange={(e) => setContent(e.target.value)}</p><p> style={{ fontWeight: isBold ? 'bold' : 'normal' }}</p><p> /></p><p> </div></p><p> );</p><p>}</p>