[javascript] 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);

This question is related to javascript reactjs keypress onkeypress

The answer is


You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1


Keypress event is deprecated, You should use Keydown event instead.

https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

handleKeyDown(event) {
    if(event.keyCode === 13) { 
        console.log('Enter key pressed')
  }
}

render() { 
    return <input type="text" onKeyDown={this.handleKeyDown} /> 
}

If you wanted to pass a dynamic param through to a function, inside a dynamic input::

<Input 
  onKeyPress={(event) => {
    if (event.key === "Enter") {
      this.doSearch(data.searchParam)
    }
  }}
  placeholder={data.placeholderText} />
/>

Hope this helps someone. :)


Late to the party, but I was trying to get this done in TypeScript and came up with this:

<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}

This prints the exact key pressed to the screen. So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").


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

There are some challenges when it comes to keypress event. Jan Wolter's article on key events is a bit old but explains well why key event detection can be hard.

A few things to note:

  1. keyCode, which, charCode have different value/meaning in keypress from keyup and keydown. They are all deprecated, however supported in major browsers.
  2. Operating system, physical keyboards, browsers(versions) could all have impact on key code/values.
  3. key and code are the recent standard. However, they are not well supported by browsers at the time of writing.

To tackle keyboard events in react apps, I implemented react-keyboard-event-handler. Please have a look.


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

onKeyDown detects keyCode events.


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


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.


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to keypress

onKeyDown event not working on divs in React How can I listen for keypress event on the whole page? How to handle the `onKeyPress` event in ReactJS? detect key press in python? jQuery Keypress Arrow Keys Submit form on pressing Enter with AngularJS How to trigger an event in input text after I stop typing/writing? How to capture Enter key press? JQuery: detect change in input field Pressing Ctrl + A in Selenium WebDriver

Examples related to onkeypress

How to handle the `onKeyPress` event in ReactJS? How to capture Enter key press? How to get text of an input text box during onKeyPress? Android - How To Override the "Back" button so it doesn't Finish() my Activity?