Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to update an object with setState in ReactJS?

How to update an object with setState in ReactJS?

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments