Add "Handling Multiple Inputs" to Forms doc (#8552)
* added "Handling Multiple Inputs" * renamed and added a codepen * simplified the example
Keyan Zhang committed
Jan 18, 2017 at 14:19 UTC
06399b8ce3fa587531e491749ba502c193b09062
1 file changed
+51
docs/docs/forms.md
+51
@@ -182,6 +182,57 @@ class FlavorForm extends React.Component {
182
183
Overall, this makes it so that `<input type="text">`, `<textarea>`, and `<select>` all work very similarly - they all accept a `value` attribute that you can use to implement a controlled component.
184
185
+## Handling Multiple Inputs
186
+
187
+When you need to handle multiple controlled `input` elements, you can add a `name` attribute to each element and let a handler function choose what to do based on the value of `event.target.name`. For example:
188
+
189
+```javascript{15,18,27,34}
190
+class Reservation extends React.Component {
191
+ constructor(props) {
192
+ super(props);
193
+ this.state = {
194
+ isGoing: false,
195
+ numberOfGuests: 0
196
+ };
197
+
198
+ this.handleInputChange = this.handleInputChange.bind(this);
199
+ }
200
+
201
+ handleInputChange(event) {
202
+ const target = event.target;
203
+ const value = target.type === 'checkbox' ? target.checked : target.value;
204
+ const name = target.name;
205
+
206
+ this.setState({
207
+ [name]: value
208
+ });
209
+ }
210
+
211
+ render() {
212
+ return (
213
+ <div>
214
+ Is going:
215
+ <input
216
+ name="isGoing"
217
+ type="checkbox"
218
+ checked={this.state.isGoing}
219
+ onChange={this.handleInputChange}
220
+ />
221
+ Number of guests:
222
+ <input
223
+ name="numberOfGuests"
224
+ type="number"
225
+ value={this.state.numberOfGuests}
226
+ onChange={this.handleInputChange}
227
+ />
228
+ </div>
229
+ );
230
+ }
231
+}
232
+```
233
+
234
+[Try it on CodePen.](https://codepen.io/keyanzhang/pen/pRENvx?editors=0010)
235
+
236
## Alternatives to Controlled Components
237
238
It can sometimes be tedious to use controlled components, because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly annoying when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, you might want to check out [uncontrolled components](/react/docs/uncontrolled-components.html), an alternative technique for implementing input forms.