Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to update a specific field in an object format state in ReactJS is to use the spread operator to create a copy of the state object, update the specific field, and then set the state with the updated object. For example:

this.state = {
  user: {
    name: 'John',
    age: 30,
    email: 'john@example.com'
  }
}

// Updating the user's email

const updatedUser = {...this.state.user, email: 'johndoe@example.com'}

this.setState({
  user: updatedUser
})

In this example, we first create a copy of the user object using the spread operator and update the email field. Then we set the state with the updated object using setState().