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>
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});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With