title: Change focus of text input with react
body: <p>My goal here is to create a form, which tabs you to the next input element when you hit the return key and submits the form when you are on the last input.</p>
  
  <p>This is being built for mobile, and since there is no option to use the 'next' button instead of the 'go keyboard' button in browser (for more information about this see <a href="https://stackoverflow.com/a/24571441/831465">this answer</a>).</p>
  
  <p>To better visualize this, here is a picture:<a href="https://i.stack.imgur.com/CDdiz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CDdiz.png" alt="enter image description here"></a></p>
  
  <p>I've also written some code, but the point here is that I am not able to catch the event in the right place, so the form gets immediately submitted after the return or when I prevent the event, the focus is changed after I hit return 2 times.</p>
  
  <p>See the example here: <a href="https://codepen.io/ofhouse/pen/Rgwzxy" rel="nofollow noreferrer">https://codepen.io/ofhouse/pen/Rgwzxy</a> (I've also pasted the code below)</p>
  
  <pre><code>class TextInput extends React.Component {
    constructor(props) {
      super(props);
      this._onKeyPress = this._onKeyPress.bind(this);
    }
  
    componentDidMount() {
      if (this.props.focus) {
        this.textInput.focus();
      }
    }
  
    componentDidUpdate(nextProps) {
      if (nextProps.focus) {
        this.textInput.focus();
      }
    }
  
    _onKeyPress(e) {
      if (e.key === 'Enter') {
        this.props.onSubmit(e);
      }
    }
  
    render() {
      return (
        &lt;div&gt;
          &lt;input
            type="text"
            onKeyPress={this._onKeyPress}
            ref={input =&gt; {
              this.textInput = input;
            }}
          /&gt;
        &lt;/div&gt;
      );
    }
  }
  
  class Application extends React.Component {
    constructor(props) {
      super(props);
  
      this.state = {
        currentElement: 0,
      };
    }
  
    _submitForm(e) {
      // If I remove this preventDefault it works, but also the form is submitted --&gt; SiteReload
      e.preventDefault();
    }
  
    _changeFocus(nextElement) {
      return e =&gt; {
        this.setState({
          currentElement: nextElement,
        });
      };
    }
  
    render() {
      const { currentElement } = this.state;
      return (
        &lt;form&gt;
  
          &lt;h1&gt;React input focus&lt;/h1&gt;
  
          &lt;TextInput focus={currentElement === 0} onSubmit={this._changeFocus(1)} /&gt;
          &lt;TextInput focus={currentElement === 1} onSubmit={this._changeFocus(0)} /&gt;
  
          &lt;div&gt;
            &lt;button type="submit" onClick={this._submitForm}&gt;Submit&lt;/button&gt;
          &lt;/div&gt;
  
        &lt;/form&gt;
      );
    }
  }
  
  ReactDOM.render(&lt;Application /&gt;, document.getElementById('app'));
  </code></pre>