Handle Change of FormControl React

Patrick Duncan picture Patrick Duncan · Jul 21, 2016 · Viewed 30.1k times · Source

Hey so I have a text box/FormControl that's supposed to update a field in a json in this.state. I was wondering if there was a better way to do onChange?

<FormControl 
  type='text' 
  placeholder='enter' 
  defaultValue={this.state.form.name}
  onChange={this.handleChange.bind(this, 'name')}
/>
</FormGroup>

`

handleChange(change, event) {
    var toChange = this.state.form;
    toChange[change] = event.target.value;
    this.setState({form: toChange});
  }

Answer

Galeel Bhasha picture Galeel Bhasha · Jul 21, 2016

Optimise the handleChange method as below. (replace 'username' with the fieldname you like...)

<FormControl 
  type='text'
  name='username' 
  placeholder='enter' 
  defaultValue={this.state.form.username}
  onChange={this.handleChange.bind(this)}
/>
</FormGroup>

handleChange(event) {
    let fieldName = event.target.name;
    let fleldVal = event.target.value;
    this.setState({form: {...this.state.form, [fieldName]: fleldVal}})
  }