Skip to content

Instantly share code, notes, and snippets.

@akshar-dave
Created November 6, 2023 11:13
Show Gist options
  • Save akshar-dave/0ae0630bafcc23f245d3ace7cee2019e to your computer and use it in GitHub Desktop.
Save akshar-dave/0ae0630bafcc23f245d3ace7cee2019e to your computer and use it in GitHub Desktop.
Keyboard Shortcut mappings in React
const useKeyboardBindings = map => {
useEffect(() => {
const handlePress = e => {
const handler = map[e.key];
if (e.repeat) return;
if (typeof handler === 'function') {
handler();
}
};
window.addEventListener('keydown', handlePress);
return () => {
window.removeEventListener('keydown', handlePress);
};
}, [map]);
};
useKeyboardBindings({
1: () => console.log(1),
2: () => console.log(2),
3: () => console.log(3),
4: () => console.log(4),
'/': () => console.log('/'),
' ': () => console.log('Space'),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment