3

Which method is better/safer, recommended in general, for iterating/mapping react's children?

this.props.children.map(c => <span>new child</span>); 

OR

React.Children.map(c => <span>new child</span>); 

1 Answer 1

7

React.Children.map is better because it handles null and undefined cases.

If children is null or undefined, returns null or undefined rather than an array.

Sign up to request clarification or add additional context in comments.

3 Comments

The docs should say "... rather than throwing an error", because that's what happens if you try doing map() on undefined or null. You don't get an (empty) array in those cases which seems to be suggested here.
@Chris I think they meant this function, not comparison to first approach. So this sentence in other words would be: "Function returns array by default but will return null or undefined if children is null or undefined".
There is some discrepancy here either way. "Rather than" suggests doing otherwise than what is normal or typical, and no map() returns an array in these cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.