Search code examples
javascriptreactjsdictionarychildrenreact-proptypes

Define proptypes for child's props


I would like to work with props of the children of an element and want to validate those props.

Is it possible to achieve this with prop-types?

export default function MyComponent(props) {

  return (
      <div>
        {React.Children.map(props.children, (c, i) => {
          // Want to do something with validated c.props.somePropThatNeedValidation (if exists of course)
          // c Is not an element that I wrote so I can't validate it there
          {React.cloneElement(c, {extras})}
        }
        )}
      </div>
  )
}


MyComponent.propTypes = {
  children: PropTypes.node,
  .
  .
  .
}

Solution

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