Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate PropTypes, with array and single children side by side

Validate children

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`.
like image 735
purii Avatar asked Feb 16 '26 20:02

purii


1 Answers

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.

like image 50
Ambroos Avatar answered Feb 18 '26 09:02

Ambroos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!