Skip to content

Instantly share code, notes, and snippets.

@codemile
Created May 19, 2021 15:01
Show Gist options
  • Save codemile/4a79b6c2b8a18c3c038051f6cb6f5e75 to your computer and use it in GitHub Desktop.
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.
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