2

I'm trying to listen to keyboard events, either onKeyPress or onKeyDown, and neither handler will fire. I know that 1. My keyboard works and 2. The same handler does work for onClick.

e.g. (using ES6 class syntax for my components)

render() {
  return (
    <div
      onKeyPress={function(e){console.log('keypress');}}
      onKeyDown={function(e){console.log('keydown');}}
      onClick={function(e){console.log('click');}}
    >
      ...
    </div>
  );
}

Only 'click' logs to the console. Not sure how the error could be coming from outside this component file, but will include more code if necessary.

Jimmy Gong
  • 1,825
  • 5
  • 20
  • 35
  • Only the element that has "focus" will receive key events. It's likely your `div` element does not have focus. – rojoca Feb 10 '16 at 00:05
  • Following up, I tried to provide focus to the div by adding the autofocus (autoFocus in jsx, but I also tried just the `autofocus` html5 version). I also tried click on it to focus on it, and still no luck. Thanks for the suggestion though, hopefully I'm closer. – Jimmy Gong Feb 10 '16 at 00:53
  • This might help: http://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it – rojoca Feb 10 '16 at 01:05
  • Using the tabindex solution works if i press tab once, but not immediately (setting it to 0). Hm. I think I'll just use window.addEventListener – Jimmy Gong Feb 10 '16 at 01:28
  • does it work when you set the div as the contenteditable=true? – gor181 Feb 10 '16 at 08:13
  • 2
    Possible duplicate of [onKeyPress event not called in ReactJS render()](https://stackoverflow.com/questions/43948234/onkeypress-event-not-called-in-reactjs-render) – Paul Sweatte Aug 04 '17 at 18:19

1 Answers1

0

If you are using class take those function out inside the class and then call them on events like onKeyPress etc events

doSomething(){}

Siddhartha
  • 29
  • 4