10

Why when I use form elements I got to put e.target.name in brackets?

Here's my code :

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

(...) 
  <div>
     <label htmlFor=""> Title : </label>
     <input type="text" name="title"  onChange={this.onChange} value={this.state.title} />
  </div>
</form>
HoCo_
  • 922
  • 3
  • 10
  • 29

1 Answers1

16

This is to dynamically update object property (when the name of the property is unknown upfront but runtime). This way you could have multiple React inputs having a different name property and using the same onChange handler to update part of the state.

Related to this.

Instead of this:

<input type="text" name="title" onChange={this.onTitleChange} value={this.state.title} />
<input type="text" name="address" onChange={this.onDescriptionChange} value={this.state.address} />
<input type="text" name="description" onChange={this.onAddressChange} value={this.state.description} />

onTitleChange (e) {
   this.setState({ title : e.target.value});
}
onAddressChange (e) {
   this.setState({ address : e.target.value});
}
onDescriptionChange (e) {
   this.setState({ description : e.target.value});
}

We can write just one handler like you presented:

<input type="text" name="title" onChange={this.onChange} value={this.state.title} />
<input type="text" name="address" onChange={this.onChange} value={this.state.address} />
<input type="text" name="description" onChange={this.onChange} value={this.state.description} />

onChange (e) {
   this.setState({ [e.target.name] : e.target.value});
}
Tomasz Mularczyk
  • 27,156
  • 17
  • 99
  • 146
  • 2
    Thanks Tomasz, so it is just about computed properties, I tought that in case of the following syntax : `onChange (e) { this.setState({ e.target.name : e.target.value}); } ` Because we invoke the " e " argument, each element would get its own value inside the e.target.name naturally. I will get an eye on documentation to understand well what is at works here – HoCo_ May 16 '18 at 17:51
  • 2
    you need square brackets to tell that this refers to dynamic key name – Tomasz Mularczyk May 16 '18 at 18:20
  • @HoCo_ You are using array-syntax to access the state Object's key, instead of prop-syntax. – joedotnot Nov 07 '19 at 14:29