Salesforce | Iterate list in LWC

|
| By Webner

In LWC, we have two ways to display the list of records in our web component

  1. for:each:
    • for:item=”currentItem”: This is used to access the current item.
    • for:index=”index”: used for accessing the current item’s index.
    • key={uniqueId}: used to assign a unique ID to each item. Regardless of which directive (for:each or Iterator) you use, we must use a key as it helps to re-render only the item that changed in the list.
  2. Iterator: We can use this to apply special behavior to the first or last item in a list.
    • First – A boolean value which indicates if the current item is the first item in the list.
    • Last – A boolean value which indicates if the current item is the last item in the list.

Below is the code of various files of “IteratorDemo” LWC:

  • IteratorDemo.html:
    lwc code
  • IteratorDemo.js:
    import { LightningElement } from 'lwc';
    export default class IteratorDemo extends LightningElement {
    contacts = [
    {
    Id: "1",
    Name: "Demo",
    Email: "Demo@gmail.com"
    },
    {
    Id: 2,
    Name: "Demo2",
    Email: "Demo2@gmail.com"
    },
    {
    Id: 3,
    Name: "Demo3",
    Email: "Demo3@gmail.com"
    }
    ] }
  • IteratorDemo.css:
    .list-first{
    border-top: 1px solid black;
    padding-top: 5px;
    }
    .list-last{
    border-bottom: 1px solid black;
    padding-bottom: 5px;
    }

Output of “IteratorDemo” LWC:
for-each

Leave a Reply

Your email address will not be published. Required fields are marked *