Given a simple component that renders its children:
class ContainerComponent extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default ContainerComponent;
Question: What should the propType of the children prop be?
When I set it as an object, it fails when I use the component with multiple children:
<ContainerComponent>
<div>1</div>
<div>2</div>
</ContainerComponent>
Warning: Failed prop type: Invalid prop
childrenof typearraysupplied toContainerComponent, expectedobject.
If I set it as an array, it will fail if I give it only one child, i.e.:
<ContainerComponent>
<div>1</div>
</ContainerComponent>
Warning: Failed prop type: Invalid prop children of type object supplied to ContainerComponent, expected array.
Please advise, should I just not bother doing a propTypes check for children elements?
Try something like this utilizing oneOfType or PropTypes.node
import PropTypes from 'prop-types'
...
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
}
or
static propTypes = {
children: PropTypes.node.isRequired,
}
For me it depends on the component. If you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:
PropTypes.oneOfType
If you want to refer to a React component then you will be looking for
PropTypes.element
Although,
PropTypes.node
describes anything that can be rendered - strings, numbers, elements or an array of these things. If this suits you then this is the way.
With very generic components, who can have many types of children, you can also use the below. However I wouldn't recommend it. As mentioned in the comments below, it does somewhat defeat the point of using PropTypes and there are usually other ways to specify what your component requires. Also bare in mind that eslint and ts may (probably) not be happy with this lack of specificity:
PropTypes.any
The PropTypes documentation has the following
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
So, you can use PropTypes.node to check for objects or arrays of objects
static propTypes = {
children: PropTypes.node.isRequired,
}