Open In App

How to update an object with setState in ReactJS?

Last Updated : 28 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

We can update an object in React using the setState() method.  Every component in React inherits the setState() method from its Base component name Component.  setState() method tells React that we are updating the state, then it will figure out what part of the state is changed, and based on that, it will bring the DOM in sync with the virtual DOM.  

We pass an object in the setState() method as an argument. The properties of that object will merge with what we have in the state object or override those properties if they already exist. 

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

App.js

Javascript




import React, { Component } from "react";
class App extends Component {
  
  // Object with one property count
  state = {
    count: 0
  };
  
  // Method to update the object
  handleIncrement = () => {
    // Updating the object with setState() method
    // by passing the object and it will override
    // the value of count property
    this.setState({ count: this.state.count + 1 })
  }
  
  render() {
    return (
      <div style={{display: 'block', width: 40, margin: 'auto'}}>
        <h1><span>{this.state.count}</span>
        </h1>
        <button onClick={this.handleIncrement}
        >Increment </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: Click on increment button to increase the value of count.

Output of above code


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads