Skip to content

Instantly share code, notes, and snippets.

@thr0wn
Created February 2, 2023 19:57
Show Gist options
  • Save thr0wn/649c7288e14324cf4a2dcce72e4fa73d to your computer and use it in GitHub Desktop.
Save thr0wn/649c7288e14324cf4a2dcce72e4fa73d to your computer and use it in GitHub Desktop.
Keydown handler in typescript
import React, { useEffect, useRef, useState } from 'react';
export const KEYCODE_ENTER = 'Enter';
export const KEYCODE_ESC = 'Escape';
export const KEYCODE_SPACEBAR = 'Space';
export const useKeyDown = (key: string) => {
const [pressed, setPressed] = useState(false);
const match = (event: KeyboardEvent) => key === event.code;
const onDown = (event: KeyboardEvent) => {
if (match(event)) setPressed(true);
};
const onUp = (event: KeyboardEvent) => {
if (match(event)) setPressed(false);
};
useEffect(() => {
window.addEventListener('keydown', onDown);
window.addEventListener('keyup', onUp);
return () => {
window.removeEventListener('keydown', onDown);
window.removeEventListener('keyup', onUp);
};
}, [key]);
return pressed;
};
export const useKeyDownCallback = (key: string, callback: () => void) => {
const pressed = useKeyDown(key);
const ref = useRef(pressed);
useEffect(() => {
if (!pressed === ref.current) {
callback();
}
ref.current = pressed;
}, [pressed]);
};
export const onKeyBoardEvent = (key: string, callback: () => void) => (event: React.KeyboardEvent) => {
if (key === event.code) {
callback();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment