This isn't necessarily a bug or a feature, more so asking for why it is implemented as it currently is.
When inside of a component, this.key is undefined, however child.key is defined and has a value within React.Children.map. I realize these point to different instances, just demonstrating the difference.
Example:
class Example extends React.Component {
render() {
console.log(this.key); // undefined
return (
<div>
{React.Children.map(this.props.children, child => {
console.log(child.key); // defined
return child;
})}
</div>
)
}
}
I expect child.key to not be readable/writeable within React.Children.map, however it is both which seems counterintuitive to the idea that this.key is undefined within the component.
It can be useful/necessary for something external to inspect the key of a child element (react-transition-group does this for instance), for the same reasons React needs the key, to identify which elements refer to the same thing conceptually. The key is a function of the element, not the component instance, and only useful in the context of where the elements are in terms of their parent. An instance shouldn't be concerned with what is above it, only itself and what's below.
I suspect though the _main_ reason the key is accessible on the element is that it needs to be _somewhere_ so that react can identify elements when it needs to reorder or move them :P
Thanks for the answer 馃憤. I'm now curious as to if it is an anti-pattern (or if it could be considered one) to use child.key when mapping over children for some use cases.
Was tinkering around with an accordion that was initially using child.key to store state on which section or child was open. Decided to change it for a specific prop however because it felt like a more generalized pattern to follow.
Most helpful comment
It can be useful/necessary for something external to inspect the key of a child element (react-transition-group does this for instance), for the same reasons React needs the key, to identify which elements refer to the same thing conceptually. The key is a function of the element, not the component instance, and only useful in the context of where the elements are in terms of their parent. An instance shouldn't be concerned with what is above it, only itself and what's below.
I suspect though the _main_ reason the key is accessible on the element is that it needs to be _somewhere_ so that react can identify elements when it needs to reorder or move them :P