Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if shift key is down React Native

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...
    }
}
like image 902
Leopold Joy Avatar asked Sep 03 '25 08:09

Leopold Joy


1 Answers

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.

like image 127
Austin Poulson Avatar answered Sep 04 '25 22:09

Austin Poulson