logoESLint React
Rules

no-array-index-key

Disallows using an item's index in the array as its key.

Full Name in eslint-plugin-react-x

react-x/no-array-index-key

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-array-index-key

Presets

x recommended recommended-typescript recommended-type-checked strict strict-typescript strict-type-checked

Rule Details

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, confusing errors.

Common Violations

Invalid

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>
  );
}

Valid

interface MyComponentProps {
  items: { id: string; name: string }[];
}

function MyComponent({ items }: MyComponentProps) {
  return (
    <ul>
      {items.map((item) => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}

Resources

Further Reading


See Also

On this page