In React v16.2.0, there is a new API call React.Children
.
I am curious whats the different between React.Children
and use children
directly.
For example, if I want to manipulate the children content, I can do the trick in both methods. example
const Child = () => (
<div>child</div>
)
class App extends React.Component {
render() {
const template1 = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child);
});
const template2 = this.props.children.map((child) => {
return React.cloneElement(child);
});
return [template1, template2];
}
}
And the result is the same.
Does anyone know what is the different?
Or what is the purpose for react team to release this API.
Thank you.
The children of React component is a node which might be undefined or null. React.Children.map is a utility function to help you handle different cases.
React.Children.map
Invokes a function on every immediate child contained within children with this set to thisArg. If children is an array it will be traversed and the function will be called for each child in the array. If children is null or undefined, this method will return null or undefined rather than an array.
You should always use React.Children.map to traverse children in your app. Use children.map throws an error when children is not an array.
Please take a look at this example to see the different
Paste this to console browser:
var children = null
chidren.map(i => {return i}) // => VM370:1 Uncaught TypeError: Cannot read property 'map' of null
React.Children.map(children, i => {return i;}) // return null
Here is the result: result
So React.Children.map will handle the case when children is null or undefined
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