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)
}

      

+3
javascript reactjs


source to share


4 answers


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

+3


source to share


Not exactly shorter, but this should work:



function thingChanged(name, value) { 
  this.setState(Object.defineProperty({}, name, {value:value}))
}

      

+2


source to share


ES6 abbreviations:

this.setState({...x});

this.setState({ x });

+2


source to share


If you are using a function thingChanged

to bind two-way data, LinkedStateMixin can help you do this with less code.

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics