key
prop should be defined at array elements used as the children of a React element
- REACT_MISSING_KEY_PROP
- Code Quality
- Medium
- react
This rule applies when the key
prop is missing at array elements used as the children of a React element.
In such a case, problems like poor rendering performance and component state loss may occur when the array elements are reordered. Also, React outputs a warning message.
Noncompliant Code Example
View with compliant examples side by sideimport { useState } from 'react';
import { fetchUsers } from './UserData.js';
export function UserList() {
const [users, setUsers] = useState([]);
async function handleClick() {
setUsers(await fetchUsers());
}
const listItems = users.map(user =>
<li>{user.name}</li> // REACT_MISSING_KEY_PROP alarm
);
return (
<>
<button onClick={handleClick}>Refresh</button>
<ul>{listItems}</ul>
</>
);
}
Compliant Code Example
View with noncompliant examples side by sideimport { useState } from 'react';
import { fetchUsers } from './UserData.js';
export function UserList() {
const [users, setUsers] = useState([]);
async function handleClick() {
setUsers(await fetchUsers());
}
const listItems = users.map(user =>
<li key={user.id}>{user.name}</li>
);
return (
<>
<button onClick={handleClick}>Refresh</button>
<ul>{listItems}</ul>
</>
);
}
Version
This rule was introduced in DeepScan 1.3.0-beta.
See
React Warning: Each child in a list should have a unique "key" prop. Check the render method of
UserList
. See https://react.dev/link/warning-keys for more information.