Created
November 6, 2023 11:13
-
-
Save akshar-dave/0ae0630bafcc23f245d3ace7cee2019e to your computer and use it in GitHub Desktop.
Keyboard Shortcut mappings in React
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
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