Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Keyboard Event Handlers All 'Null'

I'm unable to get any of the React SyntheticKeyboardEvent handlers to register anything except null for the event properties.

I've isolated the component in a fiddle and am getting the same result as in my application. Can anyone see what I'm doing wrong?

http://jsfiddle.net/kb3gN/1405/

var Hello = React.createClass({     render: function() {       return (       <div>         <p contentEditable="true"            onKeyDown={this.handleKeyDown}            onKeyUp={this.handleKeyUp}            onKeyPress={this.handleKeyPress}>Foobar</p>         <textarea            onKeyDown={this.handleKeyDown}            onKeyUp={this.handleKeyUp}            onKeyPress={this.handleKeyPress}>         </textarea>         <div>           <input type="text" name="foo"             onKeyDown={this.handleKeyDown}            onKeyUp={this.handleKeyUp}            onKeyPress={this.handleKeyPress} />         </div>       </div>       );     },      handleKeyDown: function(e) {       console.log(e);     },      handleKeyUp: function(e) {      console.log(e);     },      handleKeyPress: function(e) {      console.log(e);      } });  React.renderComponent(<Hello />, document.body); 
like image 862
cantera Avatar asked Mar 02 '14 02:03

cantera


People also ask

How can you clean up event listeners in React?

Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.

What is onClickCapture?

React onClickCapture is an event handler that gets triggered whenever we click on an element. like onclick, but the difference is that onClickCapture acts in the capture phase whereas onClick acts in the bubbling phase i.e. phases of an event.

How do you stopPropagation in React?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.


1 Answers

BinaryMuse provided the answer on IRC. Turns out it's just a quirk; you can't read the properties directly from SyntheticKeyboardEvent -- you need to specify the properties from the handler:

handleKeyUp: function(e) {  console.log(e.type, e.which, e.timeStamp); }, 

http://jsfiddle.net/BinaryMuse/B98Ar/

like image 178
cantera Avatar answered Sep 28 '22 04:09

cantera