Jason Chen Jason Chen - 4 months ago 15
React JSX Question

Reactjs add a number to a state?

say I had a Reactjs state that was organized like so:

getInitialState: function(){
return {food: ''}
}


How would I add conditional number values to that state? Say something like:

firstset: function(){
this.setState({food: +9});
}


And

secondset:function(){
this.setState({food: +10});
}


I would like to know how I would go about iterating these numbers to the state of 'food' when the
firstset
function is activated, along with the
secondset
. So the consequence of activating them both once is
9+10
, which would make
food: 19
.

Answer

You can refer to the previous state while setting it:

getInitialState: function() {
  return {
    food: 0
  }
}

firstSet: function() {
  this.setState({
    food: this.state.food + 9
  })
}

secondSet: function() {
  this.setState({
    food: this.state.food + 10
  })
}