-1

I have the following code in the costructor:

this.state = {
              messageBox: { open: false, title: 'title', content: 'content', onConfirm: function() {console.log('confirm')}, onCancel: function() {console.log('cancel')} },
            };

Now I would like to change only the open property with setState. How can I achieve this?

devamat
  • 2,293
  • 6
  • 27
  • 50

2 Answers2

1

Using Spread Operator (ES6)

this.setState({ messageBox: { ...this.state.messageBox, open: true } });

Using Object.assign

this.setState({ messageBox: Object.assign({}, this.state.messageBox, { open: true } ) });
0

This question is answered very well here:

How to update nested state properties in React

But IMO the best answers are the ones that point out that nested state is not supported directly for a reason, and should probably be avoided if possible.

davidysoards
  • 309
  • 2
  • 7