reactpatterns icon indicating copy to clipboard operation
reactpatterns copied to clipboard

a question of Children pass-through

Open yueshuiniao opened this issue 6 years ago • 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?

yueshuiniao avatar Nov 17 '17 08:11 yueshuiniao

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.

newyork-anthonyng avatar Dec 11 '17 16:12 newyork-anthonyng

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."

vardhanreddy27 avatar Jan 05 '23 08:01 vardhanreddy27