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!

3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help!
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}}}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.