no-unnecessary-key
Full Name in eslint-plugin-react-x
react-x/no-unnecessary-keyFull Name in @eslint-react/eslint-plugin
@eslint-react/no-unnecessary-keyFeatures
๐งช
Description
This rule prevents key from being placed on non-top-level elements in a list rendering.
When rendering a list of elements in React, the key prop should only be placed on the outermost element for each item in the list. Adding keys to nested child elements is redundant, can cause confusion, and may lead to subtle bugs during refactoring.
For example, if an element with a key is wrapped with a React.Fragment or another component, the key must be moved to the new wrapping element. Forgetting to remove the original key from the child element can lead to runtime warnings from React if it's duplicated, or simply leave unnecessary code. This rule helps identify and remove these redundant key props.
Examples
Failing
// A key on a child element inside a map is unnecessary
things.map(thing => (
<div key={thing.id}>
<p key="child-key">Hello</p> {/* ๐จ This key is unnecessary */}
</div>
))
// The key should be on the Fragment, not the div
things.map(thing => (
<React.Fragment key={thing.id}>
<div key={thing.id}> {/* ๐จ This key is redundant */}
{thing.name}
</div>
<div>{thing.description}</div>
</React.Fragment>
))Passing
// Key is correctly placed on the top-level element of the map
things.map(thing => <div key={thing.id}>{thing.name}</div>)
// When using Fragments, the key is correctly placed on the Fragment
things.map(thing => (
<React.Fragment key={thing.id}>
<div>{thing.name}</div>
<div>{thing.description}</div>
</React.Fragment>
))
// Static keys used to re-mount components are not affected by this rule,
// as they are not inside a list rendering context.
function ComponentWithStaticKey() {
return (
<div>
<MyComponent key={someValue} />
</div>
);
}Implementation
Further Reading
See Also
no-missing-key
Prevents missingkeyon items in list rendering.no-implicit-key
Preventskeyfrom not being explicitly specified (e.g. spreadingkeyfrom objects).no-array-index-key
Warns when an arrayindexis used as akeyprop.no-duplicate-key
Prevents duplicatekeyprops within the same list.