The library for web and native user interfaces.
Cleanup "Forms"
Paul O’Shannessy committed
Jul 16, 2013 at 23:29 UTC
602623661af939ccf340eb10dbd9edd64fb3efc0
1 file changed
+10
-3
docs/docs/06-forms.md
+10
-3
@@ -6,8 +6,10 @@ permalink: forms.html
6
prev: reusable-components.html
7
next: working-with-the-browser.html
8
---
9
+
10
Form components such as `<input>`, `<textarea>`, and `<option>` differ from other native components because they can be mutated via user interactions. These components provide interfaces that make it easier to manage forms in response to user interactions.
11
12
+
13
## Interactive Props
14
15
Form components support a few props that are affected via user interactions:
@@ -26,6 +28,7 @@ Form components allow listening for changes by setting a callback to the `onChan
28
29
Like all DOM events, the `onChange` prop is supported on all native components and can be used to listen to bubbled change events.
30
31
+
32
## Controlled Components
33
34
An `<input>` with `value` set is a *controlled* component. In a controlled `<input>`, the value of the rendered element will always reflect the `value` prop. For example:
@@ -42,12 +45,12 @@ This will render an input that always has a value of `Hello!`. Any user input wi
45
getInitialState: function() {
46
return {value: 'Hello!'};
47
},
48
+ handleChange: function(event) {
49
+ this.setState({value: event.target.value});
50
+ },
51
render: function() {
52
var value = this.state.value;
53
return <input type="text" value={value} onChange={this.handleChange} />;
48
- },
49
- handleChange: function(event) {
50
- this.setState({value: event.target.value});
54
}
55
```
56
@@ -61,6 +64,7 @@ In this example, we are simply accepting the newest value provided by the user a
64
65
This would accept user input but truncate the value to the first 140 characters.
66
67
+
68
## Uncontrolled Components
69
70
An `<input>` that does not supply a `value` (or sets it to `null`) is an *uncontrolled* component. In an uncontrolled `<input>`, the value of the rendered element will reflect the user's input. For example:
@@ -85,8 +89,10 @@ This example will function much like the **Controlled Components** example above
89
90
Likewise, `<input>` supports `defaultChecked` and `<option>` supports `defaultSelected`.
91
92
+
93
## Advanced Topics
94
95
+
96
### Why Controlled Components?
97
98
Using form components such as `<input>` in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:
@@ -107,6 +113,7 @@ Unlike HTML, React components must represent the state of the view at any point
113
114
Since this method describes the view at any point in time, the value of the text input should *always* be `Untitled`.
115
116
+
117
### Why Textarea Value?
118
119
In HTML, the value of `<textarea>` is usually set using its children: