eddyjs eddyjs - 1 month ago 12
React JSX Question

Why is `this.props.children` not an array when there's just one child?

From a design standpoint, I don't understand why

this.props.children
isn't an array by default. It makes it more difficult to work with when you have to take account that it may sometimes be a single child and sometimes an array.

I understand that using
React.Children
methods allow you to manipulation a components children in much the same way, but it seems like it would be easier to just make
this.props.children
always an array.

Answer

This post on this github issue answers your question:

The fact that it's sometimes a single child and sometimes an array is just a perf optimization. Semantically they're equivalent and we could easily just wrap the single child in an array if that was the only issue.

The real issue has to do with nested fragments.

var a = <Foo />;
var b = <Foo />;
var earlierDefinedSet = { a, b };
<Foo>
  <Prefix />
  {this.props.dataList}
  <Infix />
  {this.props.children}
  <Suffix />
  {earlierDefinedSet}
</Foo>

We want the ability to conveniently be able to prepend and concatenate sets of components. You can't just flatten one of these to an array, because you would lose the key context. The keys can only be guaranteed to be unique in the set where they were originally passed in. Not in a concatenated set...

I suggest you checkout the rest of the post/thread.