How to update nested state properties in ReactJS?
Last Updated :
28 Dec, 2020
There are the following approaches to update nested state properties in ReactJS:
- Approach 1: We can create a dummy object to perform operations on it (update properties that we want) then replace the component’s state with the updated object.
- Approach 2: We can pass the old nested object using the spread operator and then override the particular properties of the nested object.
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
Javascript
import React, { Component } from "react" ;
class App extends Component {
state = {
name: 'kapil' ,
address: {
colony: 'vaishnav nagar' ,
city: 'Jaipur' ,
state: 'Rajasthan'
}
};
handleUpdate = () => {
var address = { ... this .state.address }
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
Javascript
import React, { Component } from "react" ;
class App extends Component {
state = {
name: 'kapil' ,
address: {
colony: 'vaishnav nagar' ,
city: 'Jaipur' ,
state: 'Rajasthan'
}
};
handleUpdate = () => {
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...