Amin Meyghani Amin Meyghani - 14 days ago 5
Javascript Question

Using a single handler function to set the state of inputs in a form in React

I'm new to React and I can't find an easy way to create a single handler function to set the state of two inputs in a form. This is what I have so far:

<form onSubmit="onSave">
<input type="text" value={this.state.name} onChange={this.setValue('name')}>
<input type="text" value={this.state.bio onChange={this.setValue('bio')}>
</form>


JS

React.createClass({
getInitialState() {
return {
name: '',
bio: '',
}
},
setValue: function(key) {
const self = this;
return function(e) {
var o = {};
o[key] = e.target.value;
self.setState(o);
}
},
onSave() {
console.log(this.state);
}
});


The issue that I have is that only one input is updated. Also I'm aware of the form components out there, but I really want to know if something like this is possible, because my use case is very simple.

ray ray
Answer

If I understand the question, you could give your inputs a name and then do setState({[e.target.name]: e.target.value}).