useKeyPress
The useKeyPress
Hook allows you to listen for keyboard events in your React components.
Here's an example:
import { useState, useEffect } from 'react'
function useKeyPress(targetKey) {
const [isKeyPressed, setIsKeyPressed] = useState(false)
function downHandler({ key }) {
if (key === targetKey) {
setIsKeyPressed(true)
}
}
function upHandler({ key }) {
if (key === targetKey) {
setIsKeyPressed(false)
}
}
useEffect(() => {
window.addEventListener('keydown', downHandler)
window.addEventListener('keyup', upHandler)
return () => {
window.removeEventListener('keydown', downHandler)
window.removeEventListener('keyup', upHandler)
}
}, [targetKey])
return isKeyPressed
}
This custom hook takes a single key as a parameter and returns a boolean indicating whether that key is currently being pressed. We use the useState Hook to keep track of whether the key is pressed, and two event listeners to listen for keydown and keyup events on the window object. When the target key is pressed, we update the state variable to true, and when it is released, we update the state variable to false.
To use this custom hook, you would call it in your functional component with the desired key:
function MyComponent() {
const hPress = useKeyPress('h')
const sPress = useKeyPress('s')
const rPress = useKeyPress('r')
const fPress = useKeyPress('f')
return (
<div>
{hPress && <p>h key pressed!</p>}
{sPress && <p>s key pressed!</p>}
{rPress && <p>r key pressed!</p>}
{fPress && <p>f key pressed!</p>}
</div>
)
}
In this example, we call the useKeyPress hook with the desired key ("h", "s", "r", or "f") and use the boolean return value to conditionally render a message indicating which key was pressed.
By using the useKeyPress Hook with a single key, we can easily listen for keyboard events in our React components.