How to setState by value in React?
Is there an easier way to update the state if I have the attribute name? Something simpler:
function thingChanged(name, value) {
var x = {};
x[name] = value;
this.setState(x)
}
There is no way to further minify the code with the current ECMAScript version. Perhaps with ES6 it is possible, depending on what features the language has.
However, if you are worried about code redundancy, you can add this method to mixing and pass it across all the components you need.
Update: Thanks to @FakeRainBrigand for providing ES6 syntax that allows you to shrink your code:setState({[name]: value});
Not exactly shorter, but this should work:
function thingChanged(name, value) {
this.setState(Object.defineProperty({}, name, {value:value}))
}
ES6 abbreviations:
this.setState({...x});
this.setState({ x });
If you are using a function thingChanged
to bind two-way data, LinkedStateMixin can help you do this with less code.