eslint-plugin-react icon indicating copy to clipboard operation
eslint-plugin-react copied to clipboard

Suggestion: Rule to disallow using restricted values like "key" as a prop name

Open Sweater-Baron opened this issue 9 months ago • 2 comments

React uses key as a special prop name that you pass in when mapping over a list. If you try to access a prop named key from within a component, it will be undefined. It's easy to accidentally name a prop key and cause your code to not work. Something like the following buggy code causes no eslint errors when using this plugin's recommended ruleset. (Also, if you do this in TypeScript, the runtime value of key does not align with what the type system says is happening, since the type system believes it's guaranteed to be a string, but it actually ends up being undefined since React doesn't pass the prop through).

const MyComponent: React.FC<{
  label: string;
  key: string;
}> = ({
  label,
  key,
}) => (
  <div>
    {label}
    {key}
  </div>
);

For me personally, even though I've been working in React a long time, I'll still occasionally do this, and it takes a while to notice my mistake, since you have to notice the incorrect behavior at runtime and then chase down why it's happening. I can imagine that this could be a really difficult bug for a junior to debug.

This seems to be a fairly common issue for people, based on the traffic that this stackoverflow post gets: https://stackoverflow.com/questions/33661511/reactjs-key-undefined-when-accessed-as-a-prop

A rule for this should probably also disallow naming a prop ref, and maybe any other special React prop names that I'm not thinking of?

Could call this rule react/no-restricted-prop-names or something?

To implement this rule, it seems like a good starting point might be to copy the code from lib/rules/no-unused-prop-types.js. I'd take a crack at implementing this myself, if people think it's a good idea.

Sweater-Baron avatar Feb 07 '25 21:02 Sweater-Baron