Rules
no-duplicate-key
Full Name in eslint-plugin-react-x
react-x/no-duplicate-key
Full Name in @eslint-react/eslint-plugin
@eslint-react/no-duplicate-key
Presets
x
recommended
recommended-typescript
recommended-type-checked
Description
Disallow duplicate key
on elements in the same array or a list of children
.
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
Failing
import React from 'react';
function MyComponent () {
return [
<li key="1">Item 1</li>
<li key="1">Item 2</li>
// ^^^^^^^
// - A key must be unique. 'key="1"' is duplicated.
]
};
import React from "react";
function MyComponent() {
return (
<ul>
<li key="1">Item 1</li>
<li key="1">Item 2</li>
{/* ^^^^^^^ */}
{/* - A key must be unique. 'key="1"' is duplicated. */}
</ul>
);
}
import React from "react";
function MyComponent() {
return (
<ul>
{["a", "b"].map((id) => <li key="1">{id}</li>)}
</ul>
);
// ^^^^^^^
// - A key must be unique. 'key="1"' is duplicated.
}
Passing
import React from 'react';
function MyComponent () {
return [
<li key="1">Item 1</li>
<li key="2">Item 2</li>
]
};
import React from "react";
function MyComponent() {
return (
<ul>
<li key="1">Item 1</li>
<li key="2">Item 2</li>
</ul>
);
}
import React from "react";
function MyComponent() {
return (
<ul>
{["a", "b"].map((id) => <li key={id}>{id}</li>)}
</ul>
);
}
Implementation
Further Reading
See Also
no-missing-key
Prevents missingkey
on items in list rendering.no-implicit-key
Preventskey
from not being explicitly specified (e.g. spreadingkey
from objects).no-array-index-key
Warns when an arrayindex
is used as akey
prop.