0

I'm reading through how to create login forms & came across this method:

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

Not too sure what's going on in the setState portion of it. The array brackets are throwing me off for some reason. Can anyone elaborate on what this method is doing?

sp92
  • 873
  • 1
  • 6
  • 17

3 Answers3

6

[someExpression] is called a computed property name and is an alternative to writing this:

handleChange(e) {
  const stateUpdate = {};
  stateUpdate[e.target.name] = e.target.value;

  this.setState(stateUpdate);
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
3

That's new(ish) JavaScript syntax that allows an object literal to compute a property name from an expression. It's effectively the same as:

handleChange(e) {
  var state = {};
  state[e.target.name] = e.target.value;
  this.setState(state);
}

In this case the expression that determines the property name is e.target.name.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Assume you have form with inputs named email and password. You have state variables with same name ‘email’ and ‘password’. Now you have this function handleChange attached for onChange event of input.

When it is called for email, it will set state.email to input value similarly for other fields.

This is a new syntax where you can assign objects key in this way.

Sandip Nirmal
  • 2,283
  • 21
  • 24