Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState by value in React?

Is there a simpler way to update state if I have the name of the attribute? Something simpler than this:

function thingChanged(name, value) { 
  var x = {};
  x[name] = value;
  this.setState(x)
}
like image 969
Joe Avatar asked Jul 08 '26 07:07

Joe


2 Answers

It is not possible to further reduce the code with the current ECMAScript version. Perhaps with ES6 it might be possible, depending on what features will the language have.

However if you're worried about code redundancy, you can add that method to a mixing and refer it in all components that you need to.

Update: Thanks to @FakeRainBrigand for providing the ES6 syntax that allows the code reduction: setState({[name]: value});

like image 85
Cristik Avatar answered Jul 10 '26 22:07

Cristik


It’s not exactly shorter but this should work:

function thingChanged(name, value) { 
  this.setState(Object.defineProperty({}, name, {value:value}))
}
like image 40
David Hellsing Avatar answered Jul 10 '26 20:07

David Hellsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!