Abhilash Abhilash - 1 month ago 5
Javascript Question

why array like syntax is used when dynamically setting react state

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
??

Answer

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);
}
Comments