Linter · Rules
react/no-array-index-key
Disallow the index of an array item as its key
React uses key to tell which list item is which between two renders. An index names a position, not an item. After you insert, remove or sort items, React matches components with the wrong data. For example, an input keeps the text that was typed for another row.
The rule looks at the index parameter of array callbacks (map, flatMap, forEach, filter, find, findIndex, some, every, reduce, reduceRight) and of React.Children.map and React.Children.forEach. It also finds the index in a template literal, in a concatenation, in index.toString() and in String(index).
Configure
Off by default. To turn it on:
[lint.rules]
"react/no-array-index-key" = "error" # or "warn"
Examples
Reported:
const list = todos.map((todo, index) => <Todo key={index} {...todo} />);
const rows = users.map((user, index) => <Row key={`user-${index}`} user={user} />);
const cells = users.map((user, index) => React.cloneElement(cell, { key: String(index) }));
Not reported:
const list = todos.map(todo => <Todo key={todo.id} {...todo} />);
When not to use it
An index is a fine key for a list that's never reordered, filtered or added to.