Is there a neater way to connect an input field to a state property in React than onChange?

reactjs

Solution

React docs has your solution:

https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs

    class NameForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = {value: ''};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

   handleInputChange(event) {
    const target = event.target;    
    this.setState({
      [target.name]: target.value
    });
  }

      handleSubmit(event) {
        alert('A name was submitted: ' + this.state.value);
        event.preventDefault();
      }

      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label>
              Name:
              <input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} />
            </label>
            <label>
              Email:
              <input name="email" type="text" value={this.state.email} onChange={this.handleInputChange} />
            </label>
                  <label>
              Pet:
              <input name="country" type="text" value={this.state.country} onChange={this.handleInputChange} />
            </label>
            <input type="submit" value="Submit" />
          </form>
        );
      }
    }

Problem

So look at this code below for our example, a simple 2-way data-binding on an input field connecting the field to a property `inputValue`. But say you have a more complex page with 30 or more inputs. Are you supposed to write 30+ `onChange` handlers in the class, all with different names corresponding to the inputs like `onNameChange`, `onEmailChange`, `onPhoneChange`, and so on? Is there no neater, more implicit way to bind inputs than what I have below here? ``` React.createClass({ getInitialState() { inputValue: '' }, render() { return ( <input type='text' value={this.state.inputValue} onChange={this.onChange} /> ); }, onChange(e) { this.setState({ inputValue: e.target.value }); } }); ``` Edit: I suppose I could do this and avoid writing handlers on the class: ``` <input onChange={ e => this.setState({firstName: e.target.value}) } /> ``` Is that kosher?

Original source

Related problems