Home » Reactjs » KeyPress event handling in reactJs

KeyPress event handling in reactJs

Posted by: admin November 30, 2017 Leave a comment

Questions:
var Test = React.createClass({
     add: function(event){
         if(event.keyCode == 13){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={this.add} />    
          </div>
        );
     }
});

React.render(<Test />, document.body);

How can I make the KeyPress event work in React JS . It should alert when enter (keyCode=13) is pressed.

Answers:

I am working with React 0.14.7, use onKeyPress and event.key works well.

handleKeyPress = (event) => {
  if(event.key == 'Enter'){
    console.log('enter press here! ')
  }
}
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyPress={this.handleKeyPress} />
        </div>
     );
}

Questions:
Answers:
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

Questions:
Answers:

For me onKeyPress the e.keyCode is always 0, but e.charCode has correct value. If used onKeyDown the correct code in e.charCode.

var Title = React.createClass({
    handleTest: function(e) {
      if (e.charCode == 13) {
        alert('Enter... (KeyPress, use charCode)');
      }
      if (e.keyCode == 13) {
        alert('Enter... (KeyDown, use keyCode)');
      }
    },
    render: function() {
      return(
        <div>
          <textarea onKeyPress={this.handleTest} />
        </div>
      );
    }
  });

React Keyboard Events
https://facebook.github.io/react/docs/events.html#keyboard-events

Questions:
Answers:

React is not passing you the kind of events you might think. Rather, it is passing synthetic events.

In a brief test, event.keyCode == 0 is always true. What you want is event.charCode