chantastic/reactpatterns

a question of Children pass-through

Opened this issue · 2 comments

// option 1: extra div
return <div>{children}</div>

// option 2: unhelpful errors
return children

I try to return this.props.children directly,and there is no error. I test the version 15.4 and 16, Here is the demo.

So Is there something I misunderstood?

When trying to return multiple children and using React.Children.only, you get this error message:

React.Children.only expected to receive a single React element child.

I'm wondering if this is the helpful error that is being mentioned? It is unclear to me too.

Yes, the error message "React.Children.only expected to receive a single React element child" is the one that is displayed when using React.Children.only and attempting to return multiple children.

React.Children.only is a utility function that is used to ensure that a component only has a single child element. It is often used when a component expects to receive a single child element, but could potentially receive multiple children if the parent component is not written correctly.
image
This component expects to receive a single child element, but it could potentially receive multiple children if the parent component passes them in. For example:
image
In this case, the MyComponent would receive two children, which is not what it was designed to handle. To prevent this situation, you can use React.Children.only to ensure that the component only receives a single child:
image
If the MyComponent is passed multiple children, it will display the error message "React.Children.only expected to receive a single React element child."