Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need to put e.target.name in square brackets []? [duplicate]

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>
like image 489
HoCo_ Avatar asked May 16 '18 16:05

HoCo_


1 Answers

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});
}
like image 200
Tomasz Mularczyk Avatar answered Sep 21 '22 21:09

Tomasz Mularczyk