no-duplicate-key
Prevents duplicate 'key' props on sibling elements when rendering lists.
This rule is experimental and may change in the future or be removed. It is not recommended for use in production code at this time.
Full Name in eslint-plugin-react-x
react-x/no-duplicate-keyFull Name in @eslint-react/eslint-plugin
@eslint-react/no-duplicate-keyFeatures
🧪
Rule Details
React uses keys to identify elements in an array. If two elements have the same key, React will not be able to distinguish them. This can lead to issues with state and rendering.
Examples
Returning sibling elements with duplicate keys in an array
When multiple elements in an array use the same key, React cannot distinguish them correctly.
// Problem: Duplicate keys on sibling elements in an array
function MyComponent () {
return [
<li key="1">Item 1</li>
<li key="1">Item 2</li>
]
};// Recommended: Assign a unique key to each sibling element
function MyComponent () {
return [
<li key="1">Item 1</li>
<li key="2">Item 2</li>
]
};Writing sibling elements with duplicate keys in JSX
Sibling elements written directly in JSX with the same key will also cause React identification issues.
// Problem: Duplicate keys on sibling elements in JSX
function MyComponent() {
return (
<ul>
<li key="1">Item 1</li>
<li key="1">Item 2</li>
</ul>
);
}// Recommended: Ensure keys are unique among sibling elements
function MyComponent() {
return (
<ul>
<li key="1">Item 1</li>
<li key="2">Item 2</li>
</ul>
);
}Using a fixed key value in a map loop
Using a fixed string as a key in loops like map causes every iteration to produce elements with the same key.
// Problem: All elements in a map loop use the same key
function MyComponent() {
return (
<ul>
{["a", "b"].map((id) => <li key="1">{id}</li>)}
</ul>
);
}// Recommended: Use a unique identifier from the data as the key
function MyComponent() {
return (
<ul>
{["a", "b"].map((id) => <li key={id}>{id}</li>)}
</ul>
);
}Duplicate keys when rendering multiple lists side by side
When two or more lists are rendered as siblings under the same parent element, using array indices as keys can produce duplicate key values.
// Problem: Two lists rendered side by side both use index keys
function App({ activeItems, archivedItems }) {
return (
<div>
{activeItems.map((item, index) => (
<div key={index}>{item.name}</div>
))}
{archivedItems.map((item, index) => (
<div key={index}>{item.name}</div>
))}
</div>
);
}// Recommended: Use unique identifiers from the data
function App({ activeItems, archivedItems }) {
return (
<div>
{activeItems.map((item) => (
<div key={item.id}>{item.name}</div>
))}
{archivedItems.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}Versions
Resources
Further Reading
See Also
react-x/no-array-index-key
Disallows using an item's index in the array as its key.react-x/no-implicit-key
Prevents implicitly passing thekeyprop to components.react-x/no-missing-key
Disallows missingkeyon items in list rendering.