To validate the prop children, I use the following definition:
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
]),
Which is valid for most situations:
// PropTypes.arrayOf(PropTypes.element)
<Component>
{[
<Childcomponent />,
<Childcomponent />,
]}
</Component>
// PropTypes.element
<Component>
<Childcomponent />
</Component>
But it seems impossible to validate a structure with mixed types:
<Component>
{[
<Childcomponent />,
<Childcomponent />,
]}
<Childcomponent />
</Component>
// Failed propType: Invalid prop `children` supplied to `Component`.
this.props.children can be either a single element or an array of elements. You can do your validation like this:
const elementOrArrayOfElementPropType = PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
]);
...
propTypes: {
children: PropTypes.oneOfType([
PropTypes.arrayOf(elementOrArrayOfElementPropType),
elementOrArrayOfElementPropType,
]),
}
You basically had to go one level deeper, as you can have an array of arrays of components, just an array of components or just a component.
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