0

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!

MrShedford
  • 137
  • 1
  • 2
  • 12
  • 1
    This might help: [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – thenaamsake Nov 26 '18 at 13:00
  • 1
    Possible duplicate of [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – reisdev Nov 26 '18 at 13:01
  • 1
    You may use `immutability-helper` which is mentioned on React's official doc – im_tsm Nov 26 '18 at 13:16

2 Answers2

1

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

Titouan56
  • 6,932
  • 11
  • 37
  • 61
1

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

icewhite
  • 417
  • 3
  • 15