React.js: Identifying different inputs with one onChange handler React.js: Identifying different inputs with one onChange handler reactjs reactjs

React.js: Identifying different inputs with one onChange handler


I suggest sticking to standard HTML attributes like name on input Elements to identify your inputs. Also, you don't need to keep "total" as a separate value in state because it is composable by adding other values in your state:

var Hello = React.createClass({    getInitialState: function() {        return {input1: 0, input2: 0};    },    render: function() {        const total = this.state.input1 + this.state.input2;        return (            <div>{total}<br/>                <input type="text" value={this.state.input1} name="input1" onChange={this.handleChange} />                <input type="text" value={this.state.input2} name="input2" onChange={this.handleChange} />            </div>        );    },    handleChange: function(e) {        this.setState({[e.target.name]: e.target.value});    }});React.renderComponent(<Hello />, document.getElementById('content'));


You can use the .bind method to pre-build the parameters to the handleChange method.It would be something like:

  var Hello = React.createClass({    getInitialState: function() {        return {input1:0,                 input2:0};    },    render: function() {      var total = this.state.input1 + this.state.input2;      return (        <div>{total}<br/>          <input type="text" value={this.state.input1}                              onChange={this.handleChange.bind(this, 'input1')} />          <input type="text" value={this.state.input2}                              onChange={this.handleChange.bind(this, 'input2')} />        </div>      );    },    handleChange: function (name, e) {      var change = {};      change[name] = e.target.value;      this.setState(change);    }  });  React.renderComponent(<Hello />, document.getElementById('content'));

(I also made total be computed at render time, as it is the recommended thing to do.)


The onChange event bubbles... So you can do something like this:

// A sample formrender () {  <form onChange={setField}>    <input name="input1" />    <input name="input2" />  </form>}

And your setField method might look like this (assuming you're using ES2015 or later:

setField (e) {  this.setState({[e.target.name]: e.target.value})}

I use something similar to this in several apps, and it's pretty handy.