Search code examples
reactjsjsxreact-proptypes

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


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 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.:

<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?


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