10

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});
  }
Patrick Duncan
  • 459
  • 1
  • 5
  • 17
  • What is it that you'd like to improve about the event handler? It looks pretty ok. One thing you might want to consider though, is to not mutate the state. You could do something like `this.setState({form: {...this.state.form, [change]: event.target.value}})`. That will be necessary if you implement `shouldComponentUpdate` at some point for performance reasons. – amann Jul 21 '16 at 18:44
  • Something like that! Thanks – Patrick Duncan Jul 21 '16 at 19:03
  • I get unexpected token on the first . in ... – Patrick Duncan Jul 21 '16 at 21:01
  • What does your compile config file look like (for webpack or whatever), the ... spread syntax is still stage-0 I think which may be why it is dying. – Ben Hare Jul 25 '16 at 02:32

2 Answers2

14

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}})
  }
Galeel Bhasha
  • 1,675
  • 11
  • 19
6

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) } }
Pixel
  • 2,397
  • 3
  • 29
  • 48