2

What I'm confused about is the [event.target.name]: event.target.value in the argument for setState. I haven't seen this square bracket notation in Javascript before so I don't understand exactly why there's square brackets around the key.

onChange = event => {
    this.setState({ [event.target.name]: event.target.value })
};

Not sure what Javascript construct I'm not understanding/missing here.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 5
    Possible duplicate of [What do square brackets around a property name in an object literal mean?](https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean) – jonrsharpe Sep 25 '19 at 16:59
  • Equivalent to `const state = {}; state[event.target.name] = event.target.value; this.setState(state);`. It's just a new shorter syntax. – Emile Bergeron Sep 25 '19 at 17:13

3 Answers3

1

That just means the property name is dynamic and which is coming from event.target.name in this case.

I think the following example makes you understand it clearly

const name = 'foo';

const obj1 = {
  name: 'bar'
}

const obj2 = {
  [name]: 'bar'
}

console.log(obj1);
console.log(obj2);

This prints

{ name: 'bar' }
{ foo: 'bar' }
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
karthikdivi
  • 3,466
  • 5
  • 27
  • 46
  • Right, I understand that it's dynamic. But the author of this code put the square brackets around the key which is what I'm confused about. – Reet Chowdhary Sep 25 '19 at 17:08
  • 1
    You have to put them in brackets to use the actual value, I have updated my code with an example to show it – karthikdivi Sep 25 '19 at 17:13
-2

Actually key of an object cant be a expression or function. So as here you are trying to set the key name from the event ...this syntax is used.

-3

It looks like a WebAPI.

The target property of the Event interface is a reference to the object that dispatched the event. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

Normally a component in DOM(like input component) is passed to this function whenever its value is changed. You may see a more complex example here.

Mayeths
  • 45
  • 1
  • 8