close

How to update nested state properties in React

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to update nested state properties in React in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to update nested state properties in React

  1. How to update nested state properties in React

    to update nested state properties in React To write it in one line
    this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

  2. How to update nested state properties in React

    to update nested state properties in React To write it in one line
    this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

Method 1

To write it in one line

this.setState({ someProperty: { ...this.state.someProperty, flag: false} });

Method 2

If you are using ES2015 you have access to the Object.assign. You can use it as follows to update a nested object.

this.setState({
  someProperty: Object.assign({}, this.state.someProperty, {flag: false})
});

You merge the updated properties with the existing and use the returned object to update the state.

Edit: Added an empty object as target to the assign function to make sure the state isn’t mutated directly as carkod pointed out

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment