Single child and "onlyChild must be passed on to children with exactly one child"

If I understand React children prop correctly:

  • children usually an array, but if there is only one child, it gives one child. ( source )
  • children is “opaque”, so application code should not rely on this, apparently. ( source )
  • React.children.count returns 1 if there is only one child.
  • React.children.only should get an only child.

Based on this, I expect the following code to work:

 const Sample = ({children, ...props}) => { if (React.Children.count(children) === 1) { doSomethingWith(React.Children.only(children)); } // etc. }; <Sample>Hello, world!<Sample>; 

Instead, it throws the following error:

onlyChild should be passed on to children with exactly one child

Why?

+5
source share
1 answer

The problem is that React.Children.only expects the only child to be a valid React element, and not a displayed string or number.

I really don't understand the rationale or use case, but React 15.3.1 no less improves the error message ("React.Children.only expected to get one React child").

React issue # 1104 discusses this further.

The solution, apparently, should ignore React.Children.only and go directly to the single children element:

  if (React.Children.count(children) === 1) { doSomethingWith(children); } 
+6
source

All Articles