React: React.Children.map doesn't work with "Function as Child" Components

Created on 26 Sep 2016  路  5Comments  路  Source: facebook/react

If I create a component that accepts functions as its children, I'm not able to use React.Children.map to map through them (it returns nothing). I instead have to just use props.children.map() - but that throws an error if there's only one child.

Here's a JS Bin illustrating the issue: http://jsbin.com/fufaga/edit?js,output

I'm not sure if this is a bug, or intended functionality, or if it's just not recommended to build components this way.

(The JS Bin example is using React 15.1, but I'm experiencing this on 15.3.1 as well.)

All 5 comments

Functions are not valid React Elements, so they're discarded by React.Children.map.

@syranide @sebmarkbage Somehow this feels like it breaks the abstraction. Children are anything within the body of the JSX tag. If I do <Parent>{myfunction}</Parent>, I get a single child (no array) and if I do <Parent>{myfunc1}{myfunc2}</Parent> then I get an array. I feel like this is exactly what React.Children was intended to fix (the fact that the structure of the children produced by JSX is opaque). It kinda feels like all children (perhaps all non-null children) should be available via map.

React.Children isn't only the top level. It is also handling the recursive case. It should also retains keys properly in that scenario. Since we can't properly retain keys on some terminals, those can't be handled. Perhaps we should have a better warning in this case though.

@syranide what about SFCs, which are also simple functions?

@syranide @sebmarkbage That makes sense. If I use functions as children, I'll just handle their opaque data structure myself. Thanks for clarifying!

@yaycmyk SFCs are still represented as React Elements with the type property set to the SFC; functions as children are literally just functions, not Elements.

Was this page helpful?
0 / 5 - 0 ratings