org.sonar.l10n.javascript.rules.javascript.S6479.html Maven / Gradle / Ivy
Why is this an issue?
To optimize the rendering of React list components, a unique identifier (UID) is required for each list item. This UID lets React identify the item
throughout its lifetime. Avoid array indexes since the order of the items may change, which will cause keys to not match up between renders,
recreating the DOM. It can negatively impact performance and may cause issues with the component state.
function Blog(props) {
return (
<ul>
{props.posts.map((post, index) =>
<li key={index}> <!-- Noncompliant: When 'posts' are reordered, React will need to recreate the list DOM -->
{post.title}
</li>
)}
</ul>
);
}
To fix it, use a string or a number that uniquely identifies the list item. The key must be unique among its siblings, not globally.
If the data comes from a database, database IDs are already unique and are the best option. Otherwise, use a counter or a UUID generator.
function Blog(props) {
return (
<ul>
{props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
}
Resources
Documentation
- React Documentation - Rendering lists
- React Documentation - Recursing On Children
- MDN web docs - Crypto: randomUUID() method
- Wikipedia - UUID
Related rules
- {rule:javascript:S6477} - JSX list components should have a key property
- {rule:javascript:S6486} - JSX list components keys should match up between renders
© 2015 - 2024 Weber Informatics LLC | Privacy Policy