How to handle the `onKeyPress` event in ReactJS?
Asked Answered
P

12

341

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);
Providenciaprovident answered 7/1, 2015 at 19:34 Comment(2)
Since v0.11 React normalizes key codes into readable strings. I'd suggest using those instead of the keyCodes.Splint
@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".Ratty
D
370

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>
     );
}
Dahle answered 29/2, 2016 at 19:20 Comment(7)
and you can simutate it in tests it with : Simulate.keyPress(ReactDOM.findDOMNode(component.refs.input),{key:"Enter"});Mroz
What is this weird syntax in the handleKeyPress function declaration? Mainly the equal sign between the name and the parameter is new to me.Jotunheim
@Jotunheim its ES6 syntax and is an experimental syntax.Paleozoic
What do you mean by experimental? I thought with ES6 "functionName(param) => {}" would work?Jotunheim
@Jotunheim It's ES6 arrow function, which means function handleKeyPress(event){...}Dahle
It also binds thisComitative
Perhaps it's pedantic, but it's worth noting that it would be preferable to use the strict equality === check for event.key == 'Enter'.Dynamics
N
85

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.

Nastassia answered 6/1, 2016 at 13:26 Comment(2)
..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.Oringa
For those interested in trying out React keyEvents themselves, here's a codesandbox I created.Uund
P
58
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

Providenciaprovident answered 7/1, 2015 at 19:44 Comment(1)
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.Neri
M
46

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} /> 
}
Marutani answered 23/7, 2019 at 4:59 Comment(1)
It also supports event.key === 'Enter'. Take a look here.Marentic
I
20

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

Illene answered 8/3, 2018 at 1:5 Comment(0)
L
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>
        );
     }
});
Lyford answered 20/7, 2018 at 19:23 Comment(0)
E
15

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

useEffect(() => {
    window.addEventListener('keypress', e => {
      console.log(e.key)
    });
  }, []);
Eelworm answered 1/5, 2021 at 17:31 Comment(3)
You need to cleanup the eventlistener or it can potentially cause memory leak. See reactjs.org/docs/hooks-effect.html.Upheaval
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. postSeiden
return () => window.removeEventListener('keypress', handleKeyPress)Veratridine
R
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

Refreshment answered 7/12, 2015 at 21:18 Comment(2)
This is not affecting the question though. It doesn't change keyCode equaling 13 when Enter is pressed.Chilton
i just keep getting synthetic functions back for e.key || e.keyCode || e.charCodeSlimy
U
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").

Umbrella answered 8/2, 2018 at 19:35 Comment(1)
This doesn't seem to work. #43504464Ignace
S
8

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);
   }}
/>
Slush answered 10/12, 2022 at 4:38 Comment(0)
B
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.

Boldt answered 26/3, 2018 at 6:56 Comment(0)
S
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

Snicker answered 17/10, 2020 at 3:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.