Handle Change of FormControl React
Asked Answered
O

2

14

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});
  }
Outboard answered 21/7, 2016 at 18:34 Comment(4)
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.Kimberleekimberley
Something like that! ThanksOutboard
I get unexpected token on the first . in ...Outboard
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.Audie
C
17

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}})
  }
Cathrin answered 21/7, 2016 at 19:3 Comment(0)
G
7

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) } }
Grouping answered 20/2, 2020 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.