Last active
January 28, 2023 14:08
-
-
Save corysimmons/61c7b34f3f219acfae7b5bc18e9380bf to your computer and use it in GitHub Desktop.
A simple hook for adding hotkeys to your React app. Piggybacks on keyboardJS for a nicer interface.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import keyboardJS from 'keyboardjs' | |
import { useEffect } from 'react' | |
export default function useHotkey(key: string | string[], callback: () => void) { | |
useEffect(() => { | |
keyboardJS.bind(key, callback) | |
return () => keyboardJS.unbind(key, callback) | |
}, [key, callback]) | |
} | |
// usage | |
import useHotkey from './useHotkey' | |
export default function() { | |
useHotkey('a + b', () => console.log('you pressed a and b at the same time')) | |
return <h1>hi</h1> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment