Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS setState with multidimensional object and dynamic key

Tags:

reactjs

My State is as follows:

this.state = {
  Form: {},
  Result: {
    Duplicate: false,
    ServerError: false
  }
};

I want to dynamically add to the Form object with field values as they're entered, so I try the standard way to add dynamic keys:

handleChange(event) {
  const target = event.target;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const name = target.name;
  this.setState({
    Form[name]: value
  });
}

But this produces this syntax error:

  66 |         const name = target.name;
  67 |         this.setState({
> 68 |             Form[name]: value
     |                 ^
  69 |         });
  70 |         console.log(this.state)
  71 |     }

Is there another way to achieve this?

like image 500
StudioTime Avatar asked Jul 01 '26 17:07

StudioTime


2 Answers

I believe this is the correct way to achieve it

this.setState(prevState => ({
  Form: {
    ...prevState.Form,
    [name]: value,
  }
}));
like image 122
Lyubomir Avatar answered Jul 07 '26 09:07

Lyubomir


You've just used invalid syntax to create a dynamic object key. You need do this:

this.setState({
    Form: {
       ...this.state.Form,
       [name]: value
    }
});
like image 30
Matt Derrick Avatar answered Jul 07 '26 09:07

Matt Derrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!