352

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);
2
  • 19
    Since v0.11 React normalizes key codes into readable strings. I'd suggest using those instead of the keyCodes. Commented Jan 7, 2015 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". Commented Dec 7, 2015 at 12:19

13 Answers 13

375

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>
     );
}
Sign up to request clarification or add additional context in comments.

7 Comments

and you can simutate it in tests it with : Simulate.keyPress(ReactDOM.findDOMNode(component.refs.input),{key:"Enter"});
What do you mean by experimental? I thought with ES6 "functionName(param) => {}" would work?
@Waltari It's ES6 arrow function, which means function handleKeyPress(event){...}
It also binds this
Perhaps it's pedantic, but it's worth noting that it would be preferable to use the strict equality === check for event.key == 'Enter'.
|
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.

2 Comments

..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.
For those interested in trying out React keyEvents themselves, here's a codesandbox I created.
58
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

1 Comment

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.
52

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} /> 
}

1 Comment

It also supports event.key === 'Enter'. Take a look here.
21

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

Comments

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

Comments

16

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

useEffect(() => {
    window.addEventListener('keypress', e => {
      console.log(e.key)
    });
  }, []);

3 Comments

You need to cleanup the eventlistener or it can potentially cause memory leak. See reactjs.org/docs/hooks-effect.html.
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
return () => window.removeEventListener('keypress', handleKeyPress)
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

2 Comments

This is not affecting the question though. It doesn't change keyCode equaling 13 when Enter is pressed.
i just keep getting synthetic functions back for e.key || e.keyCode || e.charCode
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").

1 Comment

This doesn't seem to work. stackoverflow.com/questions/43503964/…
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);
   }}
/>

Comments

6

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.

Comments

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

Comments

0
const Header = () => {
    const [search, setSearch] = useState('');

    function changeHandler(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            console.log(search);
            setSearch("")
        }
    }
    return (
        <div className="header_searchBar">
            <input
                type="text"
                placeholder="Search"
                value={search}
                onKeyDown={changeHandler}
            />
        </div>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.