React hook to detect when a specific key or a combination of keys is pressed or released.
Add the hook via the CLI:
npx @novajslabs/cli add useKeyPress
Or copy and paste the code into your project:
import { useState, useEffect } from 'react'
interface KeyConfig {
key: string
ctrl?: boolean
alt?: boolean
shift?: boolean
}
export const useKeyPress = (config: KeyConfig) => {
const [keyPressed, setKeyPressed] = useState(false)
const { key: targetKey, ctrl, alt, shift } = config
const handleKeyDown = (e: KeyboardEvent) => {
const { key, ctrlKey, altKey, shiftKey } = e
if (
(!ctrl && !alt && !shift && key === targetKey) ||
(ctrl && key === targetKey && ctrlKey === ctrl) ||
(alt && key === targetKey && altKey === alt) ||
(shift && key === targetKey && shiftKey === shift)
) {
setKeyPressed(true)
}
}
const handleKeyUp = (e: KeyboardEvent) => {
const { key, ctrlKey, altKey, shiftKey } = e
if (
(!ctrl && !alt && !shift && key === targetKey) ||
(ctrl && key === targetKey && ctrlKey === ctrl) ||
(alt && key === targetKey && altKey === alt) ||
(shift && key === targetKey && shiftKey === shift)
) {
setKeyPressed(false)
}
}
useEffect(() => {
window.addEventListener('keydown', handleKeyDown)
window.addEventListener('keyup', handleKeyUp)
return () => {
window.removeEventListener('keydown', handleKeyDown)
window.removeEventListener('keyup', handleKeyUp)
}
}, [])
return keyPressed
}
React 16.8 or higher
- Name
config
- Type
- object
- Required
- required
- Description
Specifies the key and optional modifier keys to listen for.
- Name
config.key
- Type
- string
- Required
- required
- Description
The name of the key to detect.
- Name
config.ctrl
- Type
- boolean
- Optional
- optional
- Description
Represents whether the Ctrl key must be pressed (true) or not (false).
- Name
config.alt
- Type
- boolean
- Optional
- optional
- Description
Represents whether the Alt key must be pressed (true) or not (false).
- Name
config.shift
- Type
- boolean
- Optional
- optional
- Description
Represents whether the Shift key must be pressed (true) or not (false).
- Name
keyPressed
- Type
- boolean
- Description
It is true when the specified key or combination of keys is currently being pressed and false otherwise.
import { useKeyPress } from './hooks/useKeyPress'
const App = () => {
const altS = useKeyPress({ key: 's', alt: true })
return <div>{altS ? 'Saving document...' : 'Type your text here...'}</div>
}
export default App
Here are some use cases where this React hook is useful:
- Use arrow keys or combinations like Ctrl + Arrow keys for navigating through a list or a grid
- Implement shortcuts for users who rely on keyboard navigation, such as opening a menu with Alt + m
- In a web-based game, use WASD or arrow keys for movement, and Space for jumping or shooting