Created
May 19, 2021 15:01
-
-
Save codemile/4a79b6c2b8a18c3c038051f6cb6f5e75 to your computer and use it in GitHub Desktop.
React component that handles pressed/released states for a single key on the keyboard.
This file contains 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 {FC, useEffect} from 'react'; | |
export interface KeyPressedProps { | |
keyCode: string; | |
onPress: () => void; | |
onRelease: () => void; | |
} | |
export const KeyPressed: FC<KeyPressedProps> = ({ | |
keyCode, | |
onPress, | |
onRelease | |
}) => { | |
useEffect(() => { | |
const listener = (e: KeyboardEvent) => { | |
if (!e.repeat && e.key === keyCode) { | |
if (e.type === 'keydown') { | |
onPress(); | |
} | |
if (e.type === 'keyup') { | |
onRelease(); | |
} | |
} | |
}; | |
document.addEventListener('keydown', listener); | |
document.addEventListener('keyup', listener); | |
return () => { | |
document.removeEventListener('keydown', listener); | |
document.removeEventListener('keyup', listener); | |
}; | |
}, [keyCode, onPress, onRelease]); | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment