Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the `onKeyPress` event in ReactJS?

How can I make the onKeyPress event work in ReactJS? It should alert when enter (keyCode=13) is pressed.

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);
like image 654
user544079 Avatar asked Oct 19 '22 16:10

user544079


People also ask

What is onKeyPress event?

The onkeypress event occurs when the user presses a key (on the keyboard). Tip: The order of events related to the onkeypress event: onkeydown. onkeypress. onkeyup.

How do you get the enter key event in React JS?

Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input.

What is the use of onKeyPress?

The onkeypress attribute fires when the user presses a key (on the keyboard).


1 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>
     );
}
like image 331
Haven Avatar answered Oct 21 '22 06:10

Haven