16

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}
        />
    )
  }
Andrew Li
  • 55,805
  • 14
  • 125
  • 143

5 Answers5

35

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.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • What do event.keyCode || event.which do? –  Sep 12 '16 at 02:06
  • @LyManeug Actually, it's browser dependent, see [here](http://stackoverflow.com/questions/4471582/javascript-keycode-vs-which). It's a good thing to have in case a browser doesn't support `keyCode` or `which`. `||` just selects an option based on if any others are null or undefined/unsupported, basically a fallback. – Andrew Li Sep 12 '16 at 02:09
  • 1
    Just to clarify, should `onKeyUp` up should be used instead of `onKeyPress`? Confused as to which one is the right one to implement. –  Sep 12 '16 at 02:36
  • Thanks for the clarification but what do you mean by go back though? –  Sep 12 '16 at 02:40
  • @LyManeug I mean to stop interaction. Basically down and press go as soon as enter is pressed, up goes when they lift the key – Andrew Li Sep 12 '16 at 02:41
  • @LyManeug I had a problem with the code, forgot to `bind(this)`; I updated the answer with a test live example – Andrew Li Sep 12 '16 at 03:00
  • Thank you so much for the clarification and example! Really appreciate it. Working beautifully! –  Sep 12 '16 at 03:24
  • No problem @LyManeug! – Andrew Li Sep 12 '16 at 03:25
  • One more quick question if you don't mind. If I would like to link the a button to the same method as the enterPress(event), how would I determine if the button triggered it or not. For example, would like to do something like `if(code === 13 || //button triggered it)`? –  Sep 12 '16 at 03:28
  • @LyManeug I put [this](http://jsfiddle.net/rn55o9xm/2/) together by giving an ID. It should work – Andrew Li Sep 12 '16 at 03:39
  • from https://stackoverflow.com/a/43418287/7227940 they are deprecated @Andrew Li – Et7f3XIV Feb 01 '20 at 02:59
7

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>
Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
  • If I would like to link the a button to the same method as the handleKeyPress(e), how would I determine if the button triggered it or not. For example, would like to do something like `if(e.key === 'Enter' || //button triggered it)`? –  Sep 12 '16 at 03:28
  • Could you provide an example of the `render()` for the UI you're trying to create? The easiest way to do this is to have a separate `onClick` for the button and call another method, and to have the text input's `onKeyPress` also call this other method when `Enter` is pressed. – Jonny Buchanan Sep 12 '16 at 03:36
1

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

finalfreq
  • 6,830
  • 2
  • 27
  • 28
  • Sorry but before I accept the answer and upvote, could you show an example, especially how to determine if key pressed was the enter key? –  Sep 12 '16 at 02:04
1

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

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