0

Below is a function in react

For setting a state dynamically we usually do

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

But if we put the name manually then array is not needed.

handleChange: function (e) {
    this.setState({name: e.target.value})
}

Could someone tell why we put the e.target.name in array like syntax when dynamically fetching the name??

Abhilash
  • 2,864
  • 3
  • 33
  • 67
  • 2
    Possible duplicate of [Square Brackets Javascript Object Key](http://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key) – Tom Fenech Oct 28 '16 at 16:36

2 Answers2

2

That's ES6 syntax, it's called a computed key. See this answer for a bit more detail, but essentially whatever e.target.name is, it'll be set as the object key.

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

It's the same as doing this in ES5 (more verbose):

handleChange: function (e) {
    var state = {};

    state[e.target.name] = e.target.value;

    this.setState(state);
}
Community
  • 1
  • 1
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
1

Javascript evaluates the keys of objects as strings. So, [e.target.name] means access the key whose name is the value of e.target.name (cast to a string), while name: is interpreted as the key whose name is 'name'.

Wren
  • 65
  • 7