Define proptypes for child’s props

Short answer, yes, but you probably shouldn’t. 🙂

Prop-types are meant to define the contract of your component. Sort of like what static typing does for you (e.g., Typescript). If you really want to validate the children prop you could write a custom validator to do so. From the docs:

  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'

You could do something similar for your children prop (just replace customProp with children and then validate as necessary.

^^ That being said, I would strongly recommend against doing this unless absolutely necessary! The children prop is a well-known and specifically intentioned prop in the React world. Since prop-types are really just for dev sanity-checking anyway, you would be much better off investing a few minutes to write a solid unit test for your components instead.

The only valid case I can think of for this would be if you are providing a framework and want to provide helpful debugging messages for your consumers. However, good documentation and examples usually have more legs than a console warning FWIW.

Let me know if I didn’t understand your intention.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top