Search code examples
javascriptreactjsfocushandlerkeypress

How do I put a keyPress handler that can be used without having the button on focus?


I'm doing a ReactJS calculator, and I want to be able to click the numbers on my keyboard and that showing on my calculator. I wrote the following handler:

handleKeyPress = (e) => {
  const element = this.state.keys.find(obj => obj.keyCode === e.keyCode);
  console.log(element);
  console.log(e); }

The content is just to check if it works. It doesn't work, and it took me some time to notice it only workes when a button (where I previously called the handler) is focused (after I clicked it). How can I make my handler work without any button being on focus? I want it to be called when I press any key.

Here is my app: https://codesandbox.io/s/github/AldanaBRZ/javascript-calculator?file=/src/App.js


Solution

  • This code allows you to catch any key you press:

    document.addEventListener("keydown", function(e){
        var keyPressed = e.key;
        console.log(keyPressed);
    })