A generic handleChange function for React forms

A short trick while coding forms in react, where several variables are bound in to the state of the current component. The naive way of implementing it is having several handleNameChange, handleAgeChange, handleAddressChange etc. functions for all fields. You will end up with a lot of boilerplate code this way.

You can easily and cleanly avoid this by reusing the name attribute on input fields, and having a generic change handler that reads the name from the field, and updates state with the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React from 'react';
import TranslatedComponent from '../utils/TranslatedComponent.js';

class CreditCardForm extends React.Component {
  constructor() {
    super()

    this.state = {
      name: '',
      address: '',
      ccNumber: ''
    }
  }

  handleChange(e) {
    // If you are using babel, you can use ES 6 dictionary syntax { [e.target.name] = e.target.value }
    var change = {}
    change[e.target.name] = e.target.value
    this.setState(change)
  }

  render() {
    return (
      <form>
        <h2>Enter you credit card details</h2>

        <label>
          Full Name
          <input type="name" onChange={this.handleChange.bind(this)} value={this.state.name} />
        </label>

        <label>
          Home address
          <input type="address" onChange={this.handleChange.bind(this)} value={this.state.address} />
        </label>

        <label>
          Credit card number
          <input type="ccNumber" onChange={this.handleChange.bind(this)} maxlength="16" value={this.state.ccNumber} />
        </label>

        <button type="submit">Pay now</button>
      </form>
    )
  }
}

If your form gets it’s content from Redux, you can generalize the same way, but having handleChange call this.props.onChange or similar with the change object instead.