Rules
no-array-index-key
Full Name in @eslint-react/eslint-plugin
@eslint-react/no-array-index-keyFull Name in eslint-plugin-react-x
react-x/no-array-index-keyPresets
x
recommended
recommended-typescript
recommended-type-checked
strict
strict-typescript
strict-type-checked
Description
Disallows using an item's index in the array as its key.
The order of items in list rendering can change over time if an item is inserted, deleted, or the array is reordered. Using indexes as keys often leads to subtle and confusing errors.
Examples
Failing
import React from "react";
interface MyComponentProps {
items: { id: string; name: string }[];
}
function MyComponent({ items }: MyComponentProps) {
return (
<ul>
{items.map((item, index) => (
// ^^^^^
// - Do not use an item's index in the array as its key.
<li key={index}>{item.name}</li>
))}
</ul>
);
}Passing
import React from "react";
interface MyComponentProps {
items: { id: string; name: string }[];
}
function MyComponent({ items }: MyComponentProps) {
return (
<ul>
{items.map((item) => <li key={item.id}>{item.name}</li>)}
</ul>
);
}Implementation
Further Reading
See Also
no-missing-key
Prevents missingkeyon items in list rendering.no-duplicate-key
Prevents duplicatekeyon elements in the same array or a list ofchildren.no-implicit-key
Preventskeyfrom not being explicitly specified (e.g., spreadingkeyfrom objects).