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:
bunfig.toml
[lint.rules]
"react/no-array-index-key" = "error" # or "warn"Examples#
example.jsx1 problem
const list = todos.map((todo, index) => <Todo key={indexDo not use Array index in keys} {...todo} />);example.jsx2 problems
const rows = users.map((user, index) => <Row key={`user-${index}`Do not use Array index in keys} user={user} />);
const cells = users.map((user, index) => React.cloneElement(cell, { key: String(indexDo not use Array index in keys) }));example.jsxNo problems
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.