Handle Change of Formcontrol React

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

2 Answers

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

If your function is relatively simple you can simplify further,

onChange = { (event) => { this.myValue = event.target.value } }

or if you're passing up the props hierarchy, e.g.

onChange = { (event) => { this.props.onMyFunc(event.target.value) } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest