react icon indicating copy to clipboard operation
react copied to clipboard

Include key when using React.Children.map and React.Children.forEach

Open smussell opened this issue 11 years ago • 2 comments

Currently the key property is stripped from the children when calling React.Children.map and React.Children.forEach. It seems that it would be useful to retain this property, and leave it to the user to decide how to handle that.

For instance there is an example in the docs showing you to do the following when you want to retain the key while using cloneWithProps:

 cloneWithProps(originalComponent, { key : originalComponent.key });

http://facebook.github.io/react/docs/clone-with-props.html

This doesn't work if you want to loop over and clone each child because the key is already stripped. Below is some code I made to test this.

var Hello = React.createClass({

    render: function() {
        React.Children.map(this.props.children, function(child){
            console.log(child.props)
        });
        React.Children.forEach(this.props.children, function(child){
            console.log(child.props)
        });
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<Hello name="World">
    <li key="blah1" myProp="test"/>
    <li key="blah2"/>
    <li key="blah3"/>
</Hello>, document.body);

The output of the above omits the key values.

smussell avatar Jan 10 '15 00:01 smussell

I think the key and ref are stored directly on the ReactComponentElement and not in its props; trying your example with console.log(child.key) appears to work.

heyimalex avatar Jan 14 '15 18:01 heyimalex

Awesome, that does work, I didn't realize it was stored that way. Thanks.

smussell avatar Jan 14 '15 20:01 smussell