Eslint-plugin-react: `react/no-unused-prop-types` false positive if any one component doesn't use a field

Created on 2 Nov 2020  路  4Comments  路  Source: yannickcr/eslint-plugin-react

In the following example both name and placeholder are triggering the no-unused-prop-types rule, despite both being used in separate components. I _think_ the rule is triggering for name because it is unused in Comp1 and placeholder because it is unused in Comp2.

import React from "react";

type Props = {
  name: string;
  placeholder: string;
};

export const Comp1 = (props: Props): React.ReactElement => {
  const { placeholder } = props;
  return <div placeholder={placeholder} />
}

export const Comp2 = (props: Props): React.ReactElement => {
  const { name } = props;
  return <div>{name}</div>;
}

I appreciate that this example is contrived, but _I think_ is the most basic reproduction case of a more complicated manifestation of the issue. The behaviour is kind of logical but not exactly intuitive.

question typescript

All 4 comments

This seems like a correct warning to me. Reusing the type in both components means both props are required in both of them. In this case, you shouldn't be sharing the Props type at all, since clearly the two components' types do not overlap.

Thank you for the reply (and adding the labels - apologies for not doing so).

I think I can be persuaded that the warning is indicative of a code smell in most cases. I needed to keep Props in my use-case so the solution I've gone with a solution that looks a bit like this:

type HasName = {
  name: string;
}
type HasPlaceholder = {
  placeholder: string;
}

type Props = HasName & HasPlaceholder;

The reason I thought it was counter-intuitive is that the linter was telling me "this prop is unused", when I could see that it clearly _was_ being used.

Would you be happy with me raising a PR to add my contrived code as an example of incorrect code for this rule?

Absolutely, that鈥檇 be helpful!

I鈥檇 still love to understand your actual use case tho - not why you need the union type, but why the components need to use the overly broad union instead of the more granular type that matches their respective props.

PR is up.

To be clear, in my use case I don't think the components actually need to use the overly broad union; I've refactored to avoid this, which has resolved our linting error. One of the 'granular' types involved is a moderately complicated generic type from a third party library (react-final-form), which initially put me on the wrong path for identifying the cause of the linting error.

I am fairly confident that what we were doing was a bit of a code smell and the rule did help us spot the problem. Hopefully the addition to the docs will make it easier for the next person who encounters something similar.

Was this page helpful?
0 / 5 - 0 ratings