List iteration is one of those things you do all the time in Lightning Web Components (LWC), so it’s worth getting really comfortable with it.
In Salesforce Lightning Web Components, there are many scenarios where we need to iterate over or render a list of the same set of records with different data, such as different names, emails, or products.
For example, you want to show a list of contacts. Each contact should appear in a box with the same style, but with a different name and email.
In Salesforce Lightning Web Components, we have template looping to iterate over a list of the same set of records with different data.
We have two types of directives, for each and iterator, by which we can achieve template looping.
In this tutorial, I will explain how to perform list iteration in Salesforce Lightning Web Components using the directives for: each and Iterator.
What “list iteration” Means in Salesforce LWC
In Lighting Web Components, whenever we use for:each or Iterator, we need to use the key directive on the element being iterated over. The key assigns each item a unique ID, and without it, we cannot iterate.
In simple terms, list iteration in LWC means: “I have an array of data in my JavaScript file, and I want to loop over it in the HTML to show each item.”
When a list changes, the framework uses the key to re-render only the changed item. This is used for performance optimization and isn’t reflected in the DOM at run time.
Let’s see how we can use the for: each and iterator directives for list iteration in Salesforce Lightning Web Components.
Typical real‑world uses:
- Showing a list of Contacts or Opportunities in a custom component
- Rendering dynamic rows (cart items, tasks, line items)
- Adding separators, headers, or totals based on the position of items
In LWC templates, you mainly have two ways to iterate over a list:
- for:each directive – simple, clean, works for most cases
- iterator directive – slightly more advanced, gives you extra info like first/last/index
Both rely on a nested <template> tag and a key for each item, so LWC can efficiently re‑render only the changed rows.
Iterate List in Salesforce LWC With for:each
When using the for:each directive to iterate over a list, we can access the current item by using for:item=”currentItem”.
To assign a key to the first element in the nested template, use the key={uniqueId} directive.
Now, follow the steps below to create the Lightning Web Component in which we will perform list iteration using the for:each directive.
- Create the Lightning web component, and enter the code below in the JS file. In this, we will manually define an array of contact records that we will iterate over using for:each.
You can also fetch the data dynamically by calling the Apex class in the Lightning web Component.
import { LightningElement } from 'lwc';
export default class LwcForEach extends LightningEleme