Skip to content

Instantly share code, notes, and snippets.

@luiznasciment0
Last active July 15, 2021 08:16
Show Gist options
  • Save luiznasciment0/9d272d8a7ed559f5345bef97eda09339 to your computer and use it in GitHub Desktop.
Save luiznasciment0/9d272d8a7ed559f5345bef97eda09339 to your computer and use it in GitHub Desktop.
hook to detect keyboard key pressed and execute an action when this key is pressed
import { useEffect } from 'react'
type KeyPress = {
key: string
action: () => void
}
const useKeyPress = ({ key, action }: KeyPress) => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === key) action()
document.removeEventListener('keydown', onKeyDown)
}
const onKeyUp = () => {
document.addEventListener('keydown', onKeyDown, { once: true })
}
useEffect(() => {
document.addEventListener('keydown', onKeyDown)
document.addEventListener('keyup', onKeyUp)
return () => {
document.removeEventListener('keydown', onKeyDown)
document.removeEventListener('keyup', onKeyUp)
}
})
}
export default useKeyPress
/*
Usage:
useKeyPress({
key: 'ArrowDown',
action: () => {
setState(x)
}
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment