I'm currently building a large component that should only take two components as children (in this case, a TopBar and a NavBar). So far, I've tried specifying the propType for the children as this:
AppHeader.propTypes = {
/**
* AppHeader should ONLY accept TopBar and NavBar components as children.
*/
children: PropTypes.arrayOf([
PropTypes.instanceOf(TopBar),
PropTypes.instanceOf(NavBar),
]),
};
However, the PropTypes aren't working for me. I'm facing this problem with a similar component that can take a random number of two types of subcomponents.
How should I go about creating this PropTypes for the children where you specify the type of components that it can take. (This is not an enum since an enum is 'either or'/ oneOf).
Thanks so much in advance!
I didn't test this but it seems that PropTypes.arrayOf doesn't accept an Array. Instead try providing the PropTypes.oneOfType object. Then pass your array into that.
AppHeader.propTypes = {
children: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.instanceOf(TopBar),
PropTypes.instanceOf(NavBar),
])
),
};
references: https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes https://blog.logrocket.com/validating-react-component-props-with-prop-types-ef14b29963fc/