6

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?

Penny Liu
  • 7,720
  • 5
  • 40
  • 66
SubHero
  • 99
  • 6
  • It's just a React specific key that React internally uses in order to keep track of all the children in the virtual DOM tree. – Henrik Andersson Nov 19 '15 at 05:18
  • @HenrikAndersson Why does `React.Children.map` do the same? – tonix Dec 24 '19 at 11:44
  • 1
    @tonix because `React.Children` is the same as `this.props.children`. – Henrik Andersson Dec 25 '19 at 17:05
  • @HenrikAndersson I am sorry, I have not expressed myself clearly. I meant, why does `React.Children.map` returns an array of children with their keys changed as `React.Children.toArray`? – tonix Dec 26 '19 at 09:02
  • Ah, I haven't found a source that explains the `why` behind the decision but if I were to hazard a guess then it's easier for the library to fix keys and rely on themselves than on product developers. If you want to dig into it yourself the investigation starts here: https://github.com/facebook/react/blob/7dc9745427046d462506e9788878ba389e176b8a/packages/react/src/ReactChildren.js#L363 – Henrik Andersson Dec 26 '19 at 09:43

1 Answers1

5

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.

taylorstine
  • 855
  • 7
  • 16