I would like to use a variable in the setState function in a JSX file for React.
How would I restructure this code:
var name = e.target.name;
if(name == "title"){
this.setState({ title: e.target.value});
}
else if(name == "date"){
this.setState({ date: e.target.value});
}
else if(name == "amount"){
this.setState({ amount: e.target.value});
}
Into something like this (so I don't repeat myself)?
var name = e.target.name;
this.setState({ name: e.target.value});
The above syntax just sets the state of "name" and not the value of the "name" variable.
I would like to use a variable in the setState function in a JSX file for React.
How would I restructure this code:
var name = e.target.name;
if(name == "title"){
this.setState({ title: e.target.value});
}
else if(name == "date"){
this.setState({ date: e.target.value});
}
else if(name == "amount"){
this.setState({ amount: e.target.value});
}
Into something like this (so I don't repeat myself)?
var name = e.target.name;
this.setState({ name: e.target.value});
The above syntax just sets the state of "name" and not the value of the "name" variable.
Share Improve this question edited Jan 30, 2016 at 11:51 Dmitry Shvedov 3,2864 gold badges40 silver badges56 bronze badges asked Jun 1, 2015 at 0:06 sifxtremesifxtreme 4255 silver badges8 bronze badges2 Answers
Reset to default 13Easy:
var newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
var update = {};
update[e.target.name] = e.target.value;
this.setState(update);
If you're using an ES6 transpliler that supports computed property names (like Babel), you can do:
this.setState({[e.target.name]: e.target.value});