ReactJS: focus-on-next-field-when-pressing-enter-react-js

This entry is part 19 of 35 in the series React JS

See the Pen StackOverflow Answer: focus-on-next-field-when-pressing-enter-react-js by daryl (@darylw) on CodePen.0

class App extends React.Component {
  constructor() {
    super();
    this._handleKeyPress = this._handleKeyPress.bind(this);
    this._handleButtonClick = this._handleButtonClick.bind(this);
  }
  
  componentDidMount() {
    for (let x in this.refs) {
      this.refs[x].onkeypress = (e) => 
        this._handleKeyPress(e, this.refs[x]);
    }
    this.refs.name.focus();
  }
  
  _handleKeyPress(e, field) {
    // If enter key is pressed, focus next input field.
    if (e.keyCode === 13) {
      e.preventDefault();
      let next = this.refs[field.name].nextSibling;
      if (next && next.tagName === "INPUT") {
        this.refs[field.name].nextSibling.focus();
      }
    }
  }
  
  _handleButtonClick(e) {
    e.preventDefault();
    console.log('buttonClicked!');
  }
  
  render() {
    return (
      <div>
        <h1>Focus next input on Enter</h1>
        <form>
          <input type="text" name="name" ref='name' />
          <input type="text" name="email" ref='email' />
          <input type="text" name="zip_code" ref='zip_code' />
          <button onClick={this._handleButtonClick}>Submit</button>
        </form>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
Series Navigation<< ReactJS: Counter
ReactJS: Accordion >>