0

I dont have a clear concrete understanding of why we write e.target.name into the state definition statement in react. Who can explain ? thanks in advance.

checkboxChange(e) {

let state = {
  ...this.state,
  [e.target.name]: !this.state[e.target.name]
};
...

why we write

 [e.target.name]: !this.state[e.target.name]

in the state

Dragon14
  • 317
  • 6
  • 18
  • It is to set a prop of the state as the name of your checkbox. e.target.name is the name (the one you gave) of your component / checkbox. – G. Frx Feb 25 '19 at 12:18
  • This code assumes that a property name in your state object is mapped to the input name in your form fields. – AdityaParab Feb 25 '19 at 12:18

2 Answers2

2

If an input's name is "email" or "password" you can easily set that state key without defining a separate function for each input.

For email and password it would be like:

<input name="email" onChange={this._handleChange} />
<input name="password" onChange={this._handleChange} />

And the function would be

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

In your case you're setting checkbox values so the same principle applies.

João Cunha
  • 9,929
  • 4
  • 40
  • 61
1

Let's say that in your state you have something like this:

state = {
  privacyAccepted: false
}

Now, you can manage that value with a simple checkbox:

<input
  type="checkbox"
  name="privacyAccepted"
  ...
/>

Once you attach an event handler to this checkbox, you can access the target from the generated event, like:

<input
  type="checkbox"
  name="privacyAccepted"
  onChange={ this.handlePrivacy }
/>

handlePrivacy = event => {
  event.target // the checkbox element that emitted this event
}

From the target, you can access the checkbox properties, like the name, with:

handlePrivacy = event => {
  event.target.name // "privacyAccepted"
}

Being able to do this, you can then have a generic onChange event handler and use the event.target.name to access properties in the state that have the same name as your inputs:

<input
  type="checkbox"
  name="privacyAccepted"
  onChange={ this.handleChange }
/>

handleChange = event => {
  this.setState({
    [event.target.name]: event.target.value // ... or what you want here
  })
}

This [...] syntax to access an object property to set a value is called computed property and it is provided by ES6.

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23