Open In App

How to update nested state properties in ReactJS?

There are the following approaches to update nested state properties in ReactJS:

Creating React Application:



Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:



cd foldername

Project Structure: It will look like the following.

Project Structure

Approach 1: App.js




import React, { Component } from "react";
class App extends Component {
  
  // Nested object
  state = {
    name: 'kapil',
    address: {
      colony: 'vaishnav nagar',
      city: 'Jaipur',
      state: 'Rajasthan'
    }
  };
  
  handleUpdate = () => {
    // Creating a dummy object using spread operator
    var address = { ...this.state.address }
  
    // Updating the city
    address.city = 'Kota';
    this.setState({ address })
  }
  
  render() {
    return (
      <div style={{ margin: 200 }}>
        <h1>{this.state.name}</h1>
        <h1>{this.state.address.colony} {","}
          {this.state.address.city}{", "}
          {this.state.address.state}</h1>
        <button
          onClick={this.handleUpdate}
        >UpdateCity </button>
      </div>
    );
  }
}
  
export default App;

Approach 2: App.js




import React, { Component } from "react";
class App extends Component {
  
  // Nested object
  state = {
    name: 'kapil',
    address: {
      colony: 'vaishnav nagar',
      city: 'Jaipur',
      state: 'Rajasthan'
    }
  };
  
  handleUpdate = () => {
    // Overriding the city property of address object
    this.setState({ address: { ...this.state.address, city: "kota" } })
  }
  
  render() {
    return (
      <div style={{ margin: 200 }}>
        <h1>{this.state.name}</h1>
        <h1>{this.state.address.colony} {","}
          {this.state.address.city}{", "}
          {this.state.address.state}</h1>
        <button
          onClick={this.handleUpdate}
        >UpdateCity </button>
      </div>
    );
  }
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:


Article Tags :