What are the key requirements when iterating over lists of data in LWC templates?
Answer
Basics: Templates cannot run loops in JavaScript expressions, so you declare iteration in markup. Each rendered item needs a key so the engine can match old and new items during re-render, moving or updating only what changed.
How it works:
- The data property must be an array (or iterable).
- Write
<template for:each={contacts} for:item="c">and, directly on the first child element,key={c.Id}. - Inside the loop use
{c.Name}.for:index="i"exposes the index. - Alternative:
iterator:it={contacts}givesit.value,it.index,it.first,it.last, handy for separators or headers. - Template expressions are limited to property access, so compute derived values in JavaScript.
Advanced / deep dive: Keys let the diff algorithm preserve DOM elements and component instances when the list is reordered, inserted or removed. Using the index as key makes reordering destroy and recreate state (input values, child components). Keys must be unique among siblings in the loop, not globally. Because you cannot call functions or use ternaries in the template, precompute per-row values (such as a CSS class) while mapping the array. Wire data is frozen, so map to a new array rather than mutating. For large lists (thousands of rows) render a page at a time, use lightning-datatable with infinite loading, or virtualize; each rendered element has a cost. Nested loops are allowed; each level needs its own key. Empty arrays render nothing, so pair with lwc:if to show an empty state.
Code / config example:
< =>
{r.Name}
No contacts.