Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
199
rated 0 times [  200] [ 1]  / answers: 1 / hits: 147425  / 11 Years ago, thu, january 9, 2014, 12:00:00

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.


More From » reactjs

 Answers
1

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

[#73278] Wednesday, January 8, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikoguym

Total Points: 339
Total Questions: 106
Total Answers: 95

Location: Mali
Member since Sat, Feb 12, 2022
2 Years ago
nikoguym questions
Wed, Sep 22, 21, 00:00, 3 Years ago
Sun, Dec 13, 20, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;