Dan Dan - 2 months ago 6
React JSX Question

How can I simplify this react component?

I have multiple inputs, and I am trying to make an input focus the next input once it reaches maxlength.

Here is my code:

handleTextChange1(e) {
const { value, maxLength } = e.target;
if (value.length === maxLength) {
ReactDOM.findDOMNode(this.nextComponent1).focus();
}
}
handleTextChange2(e) {
const { value, maxLength } = e.target;
if (value.length === maxLength) {
ReactDOM.findDOMNode(this.nextComponent2).focus();
}
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<input onChange={this.handleTextChange1.bind(this)} maxLength="4"/>
<input ref={c => this.nextComponent1=c} onChange={this.handleTextChange2.bind(this)} maxLength="4" />
<input ref={c => this.nextComponent2=c} maxLength="4"/>
</form>
)
}


I do not want each input to have a different onChange event handler.

How can I simplify this or is there a better way to achieve what I am trying to do?

Answer

A quick simplification and to make it DRYer you could pass the next component to focus as an argument to your onChange handler.

https://jsbin.com/cakujozoga/edit?html,js,output

var App = React.createClass({
  handleSubmit: function() {},

  handleTextChange: function(nextComponent, e) {
    const { value, maxLength } = e.target;
    if (value.length === maxLength) {
       ReactDOM.findDOMNode(this.refs[nextComponent]).focus();
    }
  },

  render: function() {
    return (
       <form onSubmit={this.handleSubmit.bind(this)}>
          <input onChange={this.handleTextChange.bind(this, "nextComponent1")} maxLength="4"/>
          <input ref="nextComponent1" onChange={this.handleTextChange.bind(this, "nextComponent2")} maxLength="4" />
          <input ref="nextComponent2" maxLength="4"/>
       </form>
    )
  }
});