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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With