0

If you have an object in the state,

state = {
  item: {
    name: ''
  }
}

How to use this design pattern to access the name property of the item object?

changeMe = (e) => this.setState( {[e.target.name]: e.target.value});

I tried changing the name to item.name but it just creates a state with item.name as key.

<Form.Control name="item.name" onChange={this.onChange} defaultValue={this.state.item.name}></Form.Control>

2 Answers2

0

How about:

changeMe = (e) => this.setState( { item: {[e.target.name]: e.target.value} });
Johnny Zabala
  • 2,285
  • 1
  • 12
  • 14
  • You would also need to update the `name` of the target for this to work i.e. `name="name"` rather than `name="item.name"` – James Feb 01 '20 at 22:00
  • It works if the object only has 1 property. Somehow the item gets overwritten if i change another form field. ``` state = { item: { name: '', id: 0 } } ``` @James I already reverted it to name="name" – Klifford Agujar Feb 01 '20 at 22:01
0

You can't access deeply nested properties in this way, you can either manually split the string then recursively index into the property, or use something off the shelf e.g. lodash.set

import set from 'lodash.set';
...
changeMe = e => {
  const newState = set(this.state, e.target.name, e.target.value);
  this.setState(newState);
}
James
  • 80,725
  • 18
  • 167
  • 237