How can I detect if the shift key is currently pressed down? I have a text input, and when the user presses the enter key I only want to submit the form if they are not currently pressing the enter key (same form functionality as Facebook Messenger on desktop).
Here is my text input:
<TextInput
style={styles.input}
placeholder={'Enter message'}
onKeyPress={this.handleKeyPress}
/>
And here is the handler:
handleMessageInputKeyPress(e) {
if(e.nativeEvent.key == "Enter"){
// Now check if the SHIFT key is currently pressed or not...
}
}
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 an example using hooks:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With