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

1

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.