Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do keys change when children are used with React.Children.toArray?

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?

like image 599
SubHero Avatar asked Nov 18 '15 22:11

SubHero


People also ask

What does React children toArray do?

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.

Why each child in a list should have a unique key prop?

⚠️ 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.

What is the purpose of the key prop used in React so that?

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.

How do keys work in React?

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.


1 Answers

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.

like image 53
taylorstine Avatar answered Sep 22 '22 01:09

taylorstine