Ly Maneug Ly Maneug - 2 months ago 22
React JSX Question

ReactJS - Is there a way to trigger a method by pressing the 'Enter' key inside <input/>?

Using only

onChange
and value and while focused inside a
<input/>
, preferably without jQuery, is there a way to trigger a method by pressing the 'Enter' key? Because, would only want the user to press 'Enter' key in order to update the
name
string state.

Here is the code:

constructor(props) {
super(props);

this.state = {
name: '',
}
}

textChange(event) {
this.setState({
name: event.target.value,
})
}

//Would like to trigger this once 'Enter' key is pressed while focused inside `<input/>`
enterPressed() {
var name = this.state.name;
}

render() {
return (
<input
placeholder='Enter name'
onChange={this.textChange.bind(this)}
value={this.state.name}
/>
)
}

Answer

What you can do is use React's key events like so:

<input
    placeholder='Enter name'
    onChange={this.textChange.bind(this)}
    value={this.state.name} 
    onKeyPress={this.enterPressed.bind(this)}
/>

Now, to detect enter key, change the enterPressed function to:

enterPressed(event) {
    var code = event.keyCode || event.which;
    if(code === 13) { //13 is the enter keycode
        //Do stuff in here
    } 
}

So what this does is add an event listener to the input element. See React's Keyboard Events. The function enterPressed is then triggered on event, and now enterPressed detects the key code, and if it's 13, do some things.

Here's a fiddle demonstrating the event.


Note: The onKeyPress and onKeyDown events trigger instantaneously on user press. You can use onKeyUp to combat this.