Explain where to provide the key for dynamic children.
Nick Fitzgerald committed
Aug 27, 2014 at 10:19 UTC
18874a6054a5e56bb2c4e6c0353537a1b1f2c0e1
1 file changed
+40
docs/docs/04-multiple-components.md
+40
@@ -133,6 +133,46 @@ The situation gets more complicated when the children are shuffled around (as in
133
134
When React reconciles the keyed children, it will ensure that any child with `key` will be reordered (instead of clobbered) or destroyed (instead of reused).
135
136
+The `key` should *always* be supplied directly to the components in the array, not to the container HTML child of each component in the array:
137
+
138
+```javascript
139
+// WRONG!
140
+var ListItemWrapper = React.createClass({
141
+ render: function() {
142
+ return <li key={this.props.data.id}>{this.props.data.text}</li>;
143
+ }
144
+});
145
+var MyComponent = React.createClass({
146
+ render: function() {
147
+ return (
148
+ <ul>
149
+ {this.props.results.map(function(result) {
150
+ return <ListItemWrapper data={result}/>;
151
+ })}
152
+ </ul>
153
+ );
154
+ }
155
+});
156
+
157
+// Correct :)
158
+var ListItemWrapper = React.createClass({
159
+ render: function() {
160
+ return <li>{this.props.data.text}</li>;
161
+ }
162
+});
163
+var MyComponent = React.createClass({
164
+ render: function() {
165
+ return (
166
+ <ul>
167
+ {this.props.results.map(function(result) {
168
+ return <ListItemWrapper key={result.id} data={result}/>;
169
+ })}
170
+ </ul>
171
+ );
172
+ }
173
+});
174
+```
175
+
176
You can also key children by passing an object. The object keys will be used as `key` for each value. However it is important to remember that JavaScript does not guarantee the ordering of properties will be preserved. In practice browsers will preserve property order **except** for properties that can be parsed as a 32-bit unsigned integers. Numeric properties will be ordered sequentially and before other properties. If this happens React will render components out of order. This can be avoided by adding a string prefix to the key:
177
178
```javascript