Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.Children.map vs children.map, what's the different?

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.

like image 985
Chen-Tai Avatar asked Mar 15 '18 04:03

Chen-Tai


2 Answers

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.

like image 111
kwrush Avatar answered Sep 23 '22 15:09

kwrush


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

like image 34
Khanh Pham Avatar answered Sep 21 '22 15:09

Khanh Pham