Created
March 15, 2021 22:03
-
-
Save donavon/566cac46281bf753f2c16ba1cc90a93b to your computer and use it in GitHub Desktop.
A custom #ReactJS hook that listens for changes in the state of any key.
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 { useState, KeyboardEvent } from 'react'; | |
import useEventListener from '@use-it/event-listener'; | |
export const useKeyDown = (key: string) => { | |
const [keyDown, setKeyDown] = useState(false); | |
useEventListener('keydown', (ev: KeyboardEvent) => { | |
if (ev.key === key) { | |
setKeyDown(true); | |
} | |
}); | |
useEventListener('keyup', (ev: KeyboardEvent) => { | |
if (ev.key === key) { | |
setKeyDown(false); | |
} | |
}); | |
return keyDown; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment