If I need to know whether a key like the shift key is currently being pressed, how can I find that info? This solution should assign this info into a single variable that can be called like this:
if(shiftHeld){
//Do the thing.
}
This solution will use React Native with hooks and event listeners. You can use event listeners to detect any time a key is pressed (or unpressed), then filter the results for the key you want to use as a conditional. Here's the solution:
const [shiftHeld, setShiftHeld] = useState(false);
function downHandler({key}) {
if (key === 'Shift') {
setShiftHeld(true);
}
}
function upHandler({key}) {
if (key === 'Shift') {
setShiftHeld(false);
}
}
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, []);
This will change the state to true or false depending on whether the shift key is held down or not. Then you can plug that value in anywhere you need it. Tip: You can use this format to listen for any other key. I had a hard time finding documentation on what the keys are called. If you have trouble finding the key name, implement this code then console log key
just before the if
statement in the downHandler
.
Also, make sure you leave the listeners in a useEffect
, otherwise you'll get data leaks.
Note: The implementation above only works on web due to the event listeners used. Listening for specific key presses isn't a recommended design pattern on mobile, but if you'd like to do it anyway, try an alternative package:
import KeyEvent from 'react-native-keyevent';
useEffect(() => {
KeyEvent.onKeyDownListener((keyEvent) => {
console.log('Key Down:', keyEvent.keyCode);
});
KeyEvent.onKeyUpListener((keyEvent) => {
console.log('Key Up:', keyEvent.keyCode);
});
return () => {
KeyEvent.removeKeyDownListener();
KeyEvent.removeKeyUpListener();
};
}, []);