Source:  Twitter logo

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

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.

33 users liked answer #0dislike answer #033
Andrew Li profile pic
Andrew Li

Use onKeyPress and the resulting event object's key property, which is normalised cross-browser for you by React:

<meta charset="UTF-8">
<script src="https://unpkg.com/react@15.3.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-core@5.8.38/browser-polyfill.min.js"></script>
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
<div id="app"></div>
<script type="text/babel">

var App = React.createClass({
  getInitialState() {
    return {
      name: ''
    }
  },
  handleChange(e) {
    this.setState({name: e.target.value})
  },
  handleKeyPress(e) {
    if (e.key === 'Enter') {
      alert('Enter pressed')
    }
  },
  render() {
    return <input
      placeholder='Enter name'
      onChange={this.handleChange}
      onKeyPress={this.handleKeyPress}
      value={this.state.name}
    />
  }
})

ReactDOM.render(<App/>, document.querySelector('#app'))

</script>
6 users liked answer #1dislike answer #16
Jonny Buchanan profile pic
Jonny Buchanan

You can add a onKeyPress to your input and make it equal the function you want to execute . You would just need to make sure the key pressed was the enter key using the event that is passed to the function as an argument

Unfortunately can't just use the onchange method alone to get this result

1 users liked answer #2dislike answer #21
finalfreq profile pic
finalfreq

You just simply fire a function like this,

<input type="text"
 onKeyPress={(event) => {
    var key = event.keyCode || event.which;
    if (key === 13) {
        // perform your Logic on "enter" button 
        console.log("Enter Button has been clicked")
    }
}}
/>;
0 users liked answer #3dislike answer #30
Parth Gondaliya profile pic
Parth Gondaliya

here is an example for using onpress event according to your case:

handleKeyPress(e) {
    if(e.key === 'Enter' || e.which === 13){
      console.log('enter key pressed');
      // call your method here
     }
  }

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

when you press any key inside the input field, it calls the function handleKeyPress which is receiving an event. From that event you are checking if the pressed key is Enter key or not. Also you can use the value of input. e.g. let value = e.target.value;

0 users liked answer #4dislike answer #40
Nahid Salekin profile pic
Nahid Salekin

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).