[reactjs] 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?

This question is related to reactjs jsx react-proptypes

The answer is


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 - though bare in mind that eslint and ts may not be happy with this lack of specificity:

PropTypes.any

Example:

import React from 'react';
import PropTypes from 'prop-types';

class MenuItem extends React.Component {
    render() {
        return (
            <li>
                <a href={this.props.href}>{this.props.children}</a>
            </li>
        );
    }
}

MenuItem.defaultProps = {
    href: "/",
    children: "Main page"
};

MenuItem.propTypes = {
    href: PropTypes.string.isRequired,
    children: PropTypes.string.isRequired
};

export default MenuItem;

Picture: Shows you error in console if the expected type is different

Picture: Shows you error in console if the expected type is different


If you want to include render prop components:

  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
    PropTypes.func
  ])

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

If you want to match exactly a component type, check this

MenuPrimary.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(MenuPrimaryItem),
    PropTypes.objectOf(MenuPrimaryItem)
  ])
}

If you want to match exactly some component types, check this

const HeaderTypes = [
  PropTypes.objectOf(MenuPrimary),
  PropTypes.objectOf(UserInfo)
]

Header.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.oneOfType([...HeaderTypes])),
    ...HeaderTypes
  ])
}

Try a custom propTypes :

 const  childrenPropTypeLogic = (props, propName, componentName) => {
          const prop = props[propName];
          return React.Children
                   .toArray(prop)
                   .find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
 };


static propTypes = {

   children : childrenPropTypeLogic

}

Fiddle

_x000D_
_x000D_
const {Component, PropTypes} = React;_x000D_
_x000D_
 const  childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
             var error;_x000D_
          var prop = props[propName];_x000D_
    _x000D_
          React.Children.forEach(prop, function (child) {_x000D_
            if (child.type !== 'div') {_x000D_
              error = new Error(_x000D_
                '`' + componentName + '` only accepts children of type `div`.'_x000D_
              );_x000D_
            }_x000D_
          });_x000D_
    _x000D_
          return error;_x000D_
    };_x000D_
    _x000D_
  _x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
  static propTypes = {_x000D_
    children: childrenPropTypeLogic,_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.props.children}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
   render(){_x000D_
    return (_x000D_
    <ContainerComponent>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
      </ContainerComponent>_x000D_
    )_x000D_
   }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
_x000D_
_x000D_


The answers here don't seem to quite cover checking the children exactly. node and object are too permissive, I wanted to check the exact element. Here is what I ended up using:

  • Use oneOfType([]) to allow for single or array of children
  • Use shape and arrayOf(shape({})) for single and array of children, respectively
  • Use oneOf for the child element itself

In the end, something like this:

import PropTypes from 'prop-types'
import MyComponent from './MyComponent'

children: PropTypes.oneOfType([
  PropTypes.shape({
    type: PropTypes.oneOf([MyComponent]),
  }),
  PropTypes.arrayOf(
    PropTypes.shape({
      type: PropTypes.oneOf([MyComponent]),
    })
  ),
]).isRequired

This issue helped me figure this out more clearly: https://github.com/facebook/react/issues/2979


Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to jsx

TypeScript and React - children type? How to use componentWillMount() in React Hooks? expected assignment or function call: no-unused-expressions ReactJS You should not use <Link> outside a <Router> ReactJS - .JS vs .JSX React: Expected an assignment or function call and instead saw an expression React-Native Button style not work ReactJs: What should the PropTypes be for this.props.children? ReactJS map through Object Console logging for react?

Examples related to react-proptypes

ReactJs: What should the PropTypes be for this.props.children? React PropTypes : Allow different types of PropTypes for one prop React proptype array with shape