MrShedford
MrShedford

Reputation: 137

React: SetState not updating nested object value

My property in my state looks like this:

state: {
    styling: {
          styling: {
              card: {
                  height: auto;
   }
  }
 }
}

I want the height property to update on user input from an Input element, so I created a function like this:

  handleCardChange = (event, style) => {
let property = "styling.styling." + style;
let updatedState = {
  "styling.styling.card.height": event.target.value
}
console.log(updatedState);
this.setState(updatedState);

}

where the style parameter is a string containing the path to the property being updated, in this cased "card.height". I created an object for the new state and tried passing it into setState but it doesn't update the height property.

Anyone know how to solve this problem? I'm stumped!

Upvotes: 0

Views: 397

Answers (2)

ttncrch
ttncrch

Reputation: 7263

According your code, updatedStyle is

{
  "styling.styling.card.height": xxxx
}

whereas you want:

styling: {
    styling: {
        card: {
            height: auto;
        }
    }
}

updatedStyle would be something like:

setState(previousState => ({
  styling: {
    ...previousState.styling,
    styling: {
      ...previousState.styling.styling,
      card: {
        ...previousState.styling.styling.card,
        height: event.target.value
      }
    }
  }
})

Or use a tool like https://github.com/mweststrate/immer to make it less verbose

Upvotes: 1

icewhite
icewhite

Reputation: 417

You can't access sub-elements like that. It will add a property with a key of styling.styling.card.height to the updateState object, which isn't what you want.

If you're sure all that nesting is necessary, try this: this.setState({styling: {styling: {card: {height: event.target.value}}}})

Upvotes: 1

Related Questions