332

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);
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
user544079
  • 16,109
  • 42
  • 115
  • 171
  • 19
    Since [v0.11](http://facebook.github.io/react/blog/2014/07/17/react-v0.11.html#improved-keyboard-event-normalization) React normalizes key codes into readable strings. I'd suggest using those instead of the keyCodes. – Randy Morris Jan 07 '15 at 20:36
  • @RandyMorris react does not always normalize key codes correctly. For producing "+" will give you the key code value of 187 with shiftKey = true however the "key" value will resolve to "Unidentified". – Herr Dec 07 '15 at 12:19

12 Answers12

364

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>
     );
}
Haven
  • 7,808
  • 5
  • 25
  • 37
  • 23
    and you can simutate it in tests it with : `Simulate.keyPress(ReactDOM.findDOMNode(component.refs.input),{key:"Enter"});` – sylvain Aug 13 '16 at 15:31
  • What is this weird syntax in the handleKeyPress function declaration? Mainly the equal sign between the name and the parameter is new to me. – Waltari Jan 13 '17 at 17:55
  • @Waltari its ES6 syntax and is an experimental syntax. – anoop Jan 16 '17 at 10:58
  • 2
    What do you mean by experimental? I thought with ES6 "functionName(param) => {}" would work? – Waltari Jan 16 '17 at 13:16
  • 4
    @Waltari It's ES6 [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions), which means `function handleKeyPress(event){...}` – Haven Jan 17 '17 at 07:11
  • 2
    It also binds `this` – bhathiya-perera Aug 21 '18 at 09:35
  • 6
    Perhaps it's pedantic, but it's worth noting that it would be preferable to use the strict equality `===` check for `event.key == 'Enter'`. – Alexander Nied Jun 07 '19 at 03:10
83

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.

Edgar
  • 6,022
  • 8
  • 33
  • 66
blackchestnut
  • 1,259
  • 10
  • 15
  • 13
    ..so if you're interested in using the arrow keys and/or other non-alphanumeric keys, onKeyDown is for you as they won't return a keyChar but a keyCode. – oskare Aug 01 '16 at 17:08
  • 8
    For those interested in trying out React keyEvents themselves, here's a [codesandbox](https://codesandbox.io/s/o43839o5r6) I created. – AlienKevin May 10 '19 at 00:30
58
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

user544079
  • 16,109
  • 42
  • 115
  • 171
  • 14
    Usually a thing as the enter key is detected via onKeyUp - this allows the user to stop the interaction if he decides to. using keyPress or keyDown executes immediately. – Andreas Feb 22 '16 at 14:08
41

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} /> 
}
UserNeD
  • 1,409
  • 13
  • 14
  • 5
    It also supports `event.key === 'Enter'`. Take a look [here](https://www.w3.org/TR/uievents-key/#keys-modifier). – marcelocra Apr 14 '20 at 15:13
19

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. :)

waz
  • 1,165
  • 16
  • 31
16
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>
        );
     }
});
KiranC
  • 597
  • 6
  • 6
13

This worked for me using hooks, by accessing the window element

useEffect(() => {
    window.addEventListener('keypress', e => {
      console.log(e.key)
    });
  }, []);
SeanyMc
  • 425
  • 5
  • 10
  • You need to cleanup the eventlistener or it can potentially cause memory leak. See https://reactjs.org/docs/hooks-effect.html. – cnps Mar 28 '22 at 13:14
  • It always should be cleaned up with window.removeEventListener(...). Callbacks are defined to listen to events over time. It takes memory and some processing power from the browser and the host computer. [post](https://www.pluralsight.com/guides/how-to-cleanup-event-listeners-react) – Werthis Feb 13 '23 at 09:45
11

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

Ben
  • 4,980
  • 3
  • 43
  • 84
8

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").

vbullinger
  • 4,016
  • 3
  • 27
  • 32
  • 2
    This doesn't seem to work. https://stackoverflow.com/questions/43503964/onkeydown-event-not-working-on-divs-in-react?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – sdfsdf May 13 '18 at 21:17
7

In addition to onKeyPress being deprecated, I consider that onKeyUp is a better option than onKeyDown, since it is not until the key is released that it is executed

<Element
   onKeyUp={(e) => {
        if (e.key === "Enter") console.log('Enter has press);
   }}
/>
Pep3 Márquez
  • 183
  • 2
  • 7
5

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.

David Lin
  • 13,168
  • 5
  • 46
  • 46
4

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Subhajit Das
  • 399
  • 7
  • 19