Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

If I understand React's children prop correctly:

  • children is normally an array, but if there's only one child, it gives that single child. (source)
  • children is "opaque," so application code apparently shouldn't rely on this. (source)
  • React.children.count returns 1 if there's only one child.
  • React.children.only should get the only child.

Based on that, I would 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 must be passed a children with exactly one child

Why?

like image 406
Josh Kelley Avatar asked Aug 20 '16 19:08

Josh Kelley


1 Answers

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

I don't really understand the rationale or use case for this, but React 15.3.1 at least improves the error message ("React.Children.only expected to receive a single React element child").

React issue #1104 discusses this further.

The solution is apparently to ignore React.Children.only and go ahead and access the single children element directly:

  if (React.Children.count(children) === 1) {
    doSomethingWith(children);
  }
like image 72
Josh Kelley Avatar answered Sep 28 '22 08:09

Josh Kelley