React.js: Identifying different inputs with one onChange handler

javascript, jsx, reactjs

Solution

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'));

Problem

Curious what the right way to approach this is: ``` var Hello = React.createClass({ getInitialState: function() { return {total: 0, input1:0, input2:0}; }, render: function() { return ( <div>{this.state.total}<br/> <input type="text" value={this.state.input1} onChange={this.handleChange} /> <input type="text" value={this.state.input2} onChange={this.handleChange} /> </div> ); }, handleChange: function(e){ this.setState({ ??? : e.target.value}); t = this.state.input1 + this.state.input2; this.setState({total: t}); } }); React.renderComponent(<Hello />, document.getElementById('content')); ``` Obviously you could create separate handleChange functions to handle each different input, but that's not very nice. Similarly you could create a component just for an individual input, but I wanted to see if there's a way to do it like this.

Original source

Related problems