0

This seems to me to be a very simple issue but I can't seem to solve it.

I am trying to setState on a ReactJS component while accessing the nest state object using 2 string keys but I cannot seem to get this to work.

State: -

state = {
    first_name: {
      value: '',
    },
}

These attempts fail: -

this.setState({ [[e.target.name]['value']]: e.target.value})
this.setState({ [e.target.name['value']]: e.target.value})

e.target.name evaluates to 'first_name' so that is not the issue... I have also tried: -

this.setState({ [['first_name']['value']]: e.target.value})
this.setState({ ['first_name'['value']]: e.target.value})

All that happens is I get a new entry in the state object of "undefined". Can anyone give advice here? Thanks.

Edited:

Appears to be a duplicate of: -

How do I setState for nested array?

U4EA
  • 832
  • 1
  • 12
  • 27

1 Answers1

0

Solution found (using the spread operator)...

this.setState({
    [e.target.name]: {
      ...this.state[e.target.name],
      value: e.target.value
    },
  }
)
U4EA
  • 832
  • 1
  • 12
  • 27