Keypress events are triggered whenever a user hits any of the keys on the keyboard and some action happens on the web application. Create a custom hook called useKeyPress to listen for Key press events. Once a specific key combination is hit, show a toast or a modal on the screen.
useKeyPress
that takes in one value - the key
that you want to listen to.const shiftKey = useKeyPress('Shift');
// Here, the user listens for the shiftKey press.
Shift
and Enter
keys that, when presssed together, should open a toast
on the screen indicating that the combination has been successfully hit.react-hot-toast
which is already imported in the project.Click to reveal
Try adding eventListeners
in your custom hook for keyDown
and keyUp
events. If the key is pressed, keyDown
event will be fired. If the key is lifted, keyUp
event will be fired.
Click to reveal
Ultimately, you want to return true if the key was pressed WHILE the keyDown
event is fired. This is because you want to use true
or false
conditions to conditionally render your UI.