React: PropTypes: define children component type

Created on 15 Jul 2014  路  11Comments  路  Source: facebook/react

I was looking for something like:

propTypes: {
  children: React.PropTypes.instanceOf(OtherComponent)
}

However this doesn't work of course and couldn't find another way of doing this.

Would be nice if this was supported.

All 11 comments

Used to work. Will no longer work with the upcoming descriptor changes. @sebmarkbage has some ideas.

There are two pieces to this. The simple one is when you are expecting a single component. We should have a special propType for this.

propTypes: {
  header: React.PropTypes.componentOf(OtherComponent)
}

That's simple. Someone send a pull-request?

The second part is if you want to accept one of several unknown components that are considered compatible. In XHP in Hack we use something called categories.

The third part is when you want to combine these two types of checks with a set of items. What if you want to allow a union type? What if you want the first item to be of a certain type and the remaining items another type?

@azich has some ideas around this.

Another case is if you want to accept any composite that renders to a <td> (for example), not sure if that's covered by XHP categories.

It would be really cool to be able to verify that the right React component was passed in as a property. The docs are a little confusing, because it looks like you should be validating that the right React Message component is getting passed in:

 // An object that could be one of many types
    optionalUnion: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.number,
      React.PropTypes.instanceOf(Message)
    ]),

http://facebook.github.io/react/docs/reusable-components.html

Yea, the current work around is something like: shape({ type: oneOf([MyComponent]) })

I think we need a broader solution than testing for specific types. Usually you want it to correspond to some specific interface but the actual implementation is flexible, or have a certain set of props defined on it.

Is there any news on that?

propTypes are mostly in a sort of maintenance mode and we're not really planning to add more to them right now.

Proptypes are being phased out in favor of tools like Flow.

That's simple. Someone send a pull-request?

At least part of this is something we should "maintain".

Looks like this could be closed, the explanation is here: https://github.com/facebook/react/pull/7119

In case somebody needs this functionality, I published a module for that https://www.npmjs.com/package/react-element-proptypes

Was this page helpful?
0 / 5 - 0 ratings