patternreactCritical
ReactJs: What should the PropTypes be for this.props.children?
Viewed 0 times
whatpropsthereactjsshouldchildrenforthisproptypes
Problem
Given a simple component that renders its children:
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:
Warning: Failed prop type: Invalid prop
supplied to
If I set it as an array, it will fail if I give it only one child, i.e.:
Warning: Failed prop type: Invalid prop children of type object
supplied to ContainerComponent, expected array.
Please advise, should I just not bother doing a
class ContainerComponent extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
render() {
return (
{this.props.children}
);
}
}
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:
1
2
Warning: Failed prop type: Invalid prop
children of type arraysupplied to
ContainerComponent, expected object.If I set it as an array, it will fail if I give it only one child, i.e.:
1
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?Solution
Try something like this utilizing
or
oneOfType or PropTypes.nodeimport PropTypes from 'prop-types'
...
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
}or
static propTypes = {
children: PropTypes.node.isRequired,
}Code Snippets
import PropTypes from 'prop-types'
...
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
}static propTypes = {
children: PropTypes.node.isRequired,
}Context
Stack Overflow Q#42122522, score: 558
Revisions (0)
No revisions yet.