isHotkeyPressed
This function allows us to check if the user is currently pressing down a key or a combination of keys.
Basic Usage
Import the isHotkeyPressed function from the package:
import { isHotkeyPressed } from 'react-hotkeys-hook';
or if you are using require style syntax:
const { isHotkeyPressed } = require('react-hotkeys-hook')
// or
const isHotkeyPressed = require('react-hotkeys-hook').isHotkeyPressed
Check for pressed keys on callbacks
One common use case would be to check if the user holds down a modifier key.
Live Editor
function ExampleComponent() { const [count, setCount] = useState(0); const onClick = () => isHotkeyPressed('shift') ? setCount(count - 1) : setCount(count + 1); return ( <div> <p>The count is: {count}</p> <button onClick={onClick}>Alter the count</button> </div> ) }
Result
Loading...
You can pass an array or delimited string as the first argument to check if
multiple keys are pressed simultaneously. Commas (,) are used as the default
delimiter.
Live Editor
function ExampleComponent() { const [pressed, setPressed] = useState(false); // You can also pass a string with delimiters like 'shift,a' const onClick = () => setPressed(isHotkeyPressed(['shift', 'a'])); return ( <div> <p>The hotkey was: {pressed ? 'pressed' : 'not pressed'}</p> <button onClick={onClick}>Check if hotkey is pressed</button> </div> ) }
Result
Loading...