1

I have defined a variable which will paste value as key inside userInfo.

this.state = {
      userInfo: {
        firstName: "",
        lastName: "",
        email: ""
      }
}
//_________________________________________
onChange = (e)=>{
    var stateChild = e.target.name // stateChild here is variable which will return (firstname, lastName or email) of userInfo
    var userInfo = {
     // ...this.state.userInfo
    }
    userInfo.stateChild = e.target.value; //  I want to paste state child's value here
    console.log(userInfo.stateChild);
}

1 Answer 1

1

I don't any setState in your handler. Have you tried:

this.state = {
  userInfo: {
    firstName: "",
    lastName: "",
    email: ""
  }
};

onChange = e => {
  this.setState(prevState => ({
    userInfo: {
      ...prevState.userInfo,
      [e.target.name]: e.target.value
    }
  }));
};
Sign up to request clarification or add additional context in comments.

4 Comments

using this it created new key inside userInfo. i expect to modify the value of the key that match to e.target.name
what is the new key created?
i mean if e.target .name = firstName, it did't pass value to the firstName. it seem create new firstName.
No, it can't be two the same keys in object :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.