user3559233
user3559233

Reputation: 105

Change state object variable from form input - ReactJS

I have a state:

state = {
   obj1: {
       name: "",
       message: "",
   }
}

I have a form:

<form>
<input id={obj1.name} onChange={this.handleChange}/>
<input id={obj1.message} onChange={this.handleChange}/>
</form>

on handleChange:

handleChange(e) {
    const {id, value} = e.target
    this.setState({[id]:value});

}

Instead of updating the obj1 in the state, it will create a new state variable and obj1 doesn't get updated. [id] : value works on state variables that are not objects. How can I achieve setting a new state in an object through a form change?

Upvotes: 1

Views: 1046

Answers (1)

Eric McWinNEr
Eric McWinNEr

Reputation: 533

Ok, the thing to take away is - there's a second version of the setState method that uses a callback with the old state as a parameter. It goes something like this:

this.setState(state => ({
  // ... Do your manipulation here
}))

With this, you'll be able to "update" the state without replacing it. Try to figure it out yourself using just this hint :)

If you could, kudos! You're awesome! Check out the sandbox of what I did and let's know if you did it differently. If you couldn't, no worries, you're definitely awesome! Still checkout the sandbox here:

https://codesandbox.io/s/frosty-https-rtwr7?file=/src/ClassState.js

Upvotes: 1

Related Questions