'How to check if a key is pressed/held down using event listeners and hooks in React Native?

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.
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1