Eslint-plugin-react: [react/prop-types] False positive when wrapped with React.memo

Created on 20 Aug 2020  路  5Comments  路  Source: yannickcr/eslint-plugin-react

Using version 7.20.6.

I have a TypeScript component like:

export default React.memo(function AppIcon({
  icon,
  className,
  title,
  spinning,
}: {
  icon: string | IconDefinition;
  className?: string;
  title?: string;
  spinning?: boolean;
}) {
  if (typeof icon === 'string') {
    return (
      <span
        className={clsx(
          icon,
          'app-icon',
          'no-pointer-events',
          className,
          spinning ? 'fa-spin' : false
        )}
        title={title}
      />
    );
  } else {
    return (
      <FontAwesomeIcon
        className={className ? 'app-icon ' + className : 'app-icon'}
        icon={icon}
        title={title}
        spin={spinning}
      />
    );
  }
});

This falls afoul of react/prop-types:

  11:3  error  'icon' is missing in props validation       react/prop-types
  12:3  error  'className' is missing in props validation  react/prop-types
  13:3  error  'title' is missing in props validation      react/prop-types
  14:3  error  'spinning' is missing in props validation   react/prop-types

However if I move the function declaration out of the React.memo call and then just have export default React.memo(AppIcon), the warning goes away.

bug help wanted typescript

Most helpful comment

I am having a similar problem. Strangely, I do not get false positives when just using memo, but when combining memo and forwardRef.

Also using Typescript:

type FooProps = { x: string; y: number };
const Foo = memo(
  forwardRef<HTMLDivElement, FooProps>(function Foo({ x, y }: FooProps, ref) {
    return (
      <div ref={ref}>
        {x} {y}
      </div>
    );
  })
);

I get

'x' is missing in props validation eslint(react/prop-types)
'y' is missing in props validation eslint(react/prop-types)

All 5 comments

I assume that if the warning goes away, it's because you have AppIcon.propTypes = somewhere?

ah, this is typescript, so it's using the types. Indeed, this seems like a bug in prop types detection.

I'll take a look this issue.

I am having a similar problem. Strangely, I do not get false positives when just using memo, but when combining memo and forwardRef.

Also using Typescript:

type FooProps = { x: string; y: number };
const Foo = memo(
  forwardRef<HTMLDivElement, FooProps>(function Foo({ x, y }: FooProps, ref) {
    return (
      <div ref={ref}>
        {x} {y}
      </div>
    );
  })
);

I get

'x' is missing in props validation eslint(react/prop-types)
'y' is missing in props validation eslint(react/prop-types)

Use can use the following workaround:

export const memo: <T>(c: T) => T = React.memo;

So the props type will be correctly preserved.

Was this page helpful?
0 / 5 - 0 ratings