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
47
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
// let change = { [e.target.name] = e.target.value }
let change = {}
change[e.target.name] = e.target.value
this.setState(change)
}
render() {
return (
<form>
<h2>Enter your 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 you use redux, you can generalize the code using the same pattern. All you need to change
is having handleChange
call this.props.onChange
to propagate the value to the parent
component.