19

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>
0

1 Answer 1

22

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});
}
3
  • 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_
    Commented May 16, 2018 at 17:51
  • 2
    you need square brackets to tell that this refers to dynamic key name Commented May 16, 2018 at 18:20
  • @HoCo_ You are using array-syntax to access the state Object's key, instead of prop-syntax.
    – joedotnot
    Commented Nov 7, 2019 at 14:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.