Dynamic State Changing in React.js

// Jun 13, 2015

One of the headaches I had with React was trying to figure out a general function that could update any state associated with the element that updated it. There were a few initial issues that I faced:


  • How could I distinguish which state was associated with which element?
  • How could one function change any state for any element?
  • What if the state has nested attributes? Such as a `user` state

  • The following are two functions that I’ve spent some time coming up with. Both will dynamically change any state so long as the parameters are passed to them.

    changeStateAttributeValue changes a single attributes on a given state, i.e. changing the email attribute on a state called user:

    changeStateAttributeValue: function(stateName, attributeKey, attributeValue) {
      var newState = this.state; 
      var stateBeingChanged = this.state[stateName];
      stateBeingChanged[attributeKey] = attributeValue;
      newState[stateName] = stateBeingChanged;
      this.setState(newState);
    }


    changeState simply changes a single state on a component given the state name and it’s new value:

    changeState: function(stateName, value) {
      var newState = {};
      newState[stateName] = value;
      this.setState(newState);
    }


    I wish I would have had this code to begin with! This would have saved so much time! DRY FTW.