Skip to content

Instantly share code, notes, and snippets.

@donavon
Created March 15, 2021 22:03
Show Gist options
  • Save donavon/566cac46281bf753f2c16ba1cc90a93b to your computer and use it in GitHub Desktop.
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.
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