to call onChange event after pressing Enter key to call onChange event after pressing Enter key javascript javascript

to call onChange event after pressing Enter key


According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.

var Input = React.createClass({  render: function () {    return <input type="text" onKeyDown={this._handleKeyDown} />;  },  _handleKeyDown: function(e) {    if (e.key === 'Enter') {      console.log('do validate');    }  }});

Update: Use React.Component

Here is the code using React.Component which does the same thing

class Input extends React.Component {  _handleKeyDown = (e) => {    if (e.key === 'Enter') {      console.log('do validate');    }  }  render() {    return <input type="text" onKeyDown={this._handleKeyDown} />  }}

Here is the jsfiddle.

Update 2: Use a functional component

const Input = () => {  const handleKeyDown = (event) => {    if (event.key === 'Enter') {      console.log('do validate')    }  }  return <input type="text" onKeyDown={handleKeyDown} />}


You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().

<input    type="text"    placeholder="Search..."    onChange={event => {this.setState({query: event.target.value})}}    onKeyPress={event => {                if (event.key === 'Enter') {                  this.search()                }              }}/>


pressing Enter when the focus in on a form control (input) normally triggers a submit (onSubmit) event on the form itself (not the input) so you could bind your this.handleInput to the form onSubmit.

Alternatively you could bind it to the blur (onBlur) event on the input which happens when the focus is removed (e.g. tabbing to the next element that can get focus)