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

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


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});}