If I have a react component with children and I call React.Children.toArray
on these children, why does the objects in the array have keys that are prepended with .$
var Child = React.createClass({
render: function() {
console.log(React.Children.toArray(this.props.children)[0].key);
return <div>{this.props.children}</div>
}
});
var Container = React.createClass({
render: function() {
return <Child><div key={1}>1</div></Child>
}
});
ReactDOM.render(<Container />, document.getElementById('container'));
This logs .$1
to the console. Why is the key changed from 1
to .$1
?
Children. toArray. Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.
⚠️ Warning: Each child in a list should have a unique “key” prop. This is because React uses a unique “key” prop on each child of the list to create a relationship between the component and the DOM. This is to ensure that react re-renders the child correctly next time.
React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM.
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.
See the note below https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
Note: React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element's key is scoped to the input array containing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With