close

How to handle the `onKeyPress` event in ReactJS?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to handle the onKeyPress event in ReactJS? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to handle the onKeyPress event in ReactJS ?

  1. How to handle the onKeyPress event in ReactJS ?

    handle the onKeyPress event in ReactJS 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

  2. handle the onKeyPress event in ReactJS

    handle the onKeyPress event in ReactJS 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

Method 1

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>
     );
}

Method 2

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

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment