HiveBrain v1.2.0
Get Started
← Back to all entries
patternreactCritical

ReactJs: What should the PropTypes be for this.props.children?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whatpropsthereactjsshouldchildrenforthisproptypes

Problem

Given a simple component that renders its children:

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 array
supplied 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 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,
}

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.