ljharb / prop-types-tools

Custom React PropType validators
MIT License
671 stars 50 forks source link

`componentWithName` fails when used with `childrenOf` and `forwardRef` #64

Closed leepowelldev closed 5 years ago

leepowelldev commented 5 years ago

Consider the following:

const Foo = () => {
 // ...
}

Foo.displayName = 'Foo';

const Bar = () => {
  // ...
}

Bar.propTypes = {
  children: childrenOf(componentWithName("Foo"))
}

When used like this, childrenOf and componentWithName work as expected. However, if we wrap Foo in a forwardRef wrapper like so:

const Foo = React.forwardRef(() => {
 // ...
});

Foo.displayName = 'Foo';

const Bar = () => {
  // ...
}

Bar.propTypes = {
  children: childrenOf(componentWithName("Foo"))
}

Then we receive the following warning:

Warning: Failed prop type: `Bar.children` only accepts components named Foo, got null

I believe this is down to this helper function only checking that the component is a function, when it becomes an object after it's wrapped in the forwardRef. Would there be any possibility of checking that the component type is a function or an object?

https://github.com/airbnb/prop-types/blob/5a08d03a74d2dbbf05455de47c23783d46929c3f/src/helpers/getComponentName.js#L7

ljharb commented 5 years ago

What version of react and react-dom do you have? I believe this is a bug in ForwardRef itself that react has fixed.

ljharb commented 5 years ago

oh, although good point, it’s probably exactly what you indicated. I’ll take a look.