-1

When I used to setState the value for the User Name statically, I used to use the below code to set the value in the variable name.

this.setState({ 'userName' : event.target.value })

but the same when I used to set the same value in the same key name but this time dynamically.

In my HTML attribute I set the name as userName and onChange I call the function with the event. In that event.target.name I get the userName and event.target.value I get the value that I typed but during the setState, the below code did not work:

this.setState({ event.target.name : event.target.value })

Instead of that, I used to set the key by using [event.targe.name] that's working fine:

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

Actually what I need is, what is the difference between the above two codes and how does it work in statically and dynamically?

technophyle
  • 7,972
  • 6
  • 29
  • 50
Raghul SK
  • 1,256
  • 5
  • 22
  • 30
  • Does this answer your question? [Wy we need to put e.target.name in square brackets \[\]?](https://stackoverflow.com/questions/50376353/wy-we-need-to-put-e-target-name-in-square-brackets) – blueseal Feb 11 '20 at 08:09

1 Answers1

3

The following is a syntax error:

this.setState({ event.target.name : event.target.value })

The following means the value of event.target.name will be the key name:

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

In other words:

  • { name: value } means object.name = value, which means assign value to "name" key.
  • { [name]: value } means object[name] = value, which means assign value to the key with the value of name.
technophyle
  • 7,972
  • 6
  • 29
  • 50