Chapter 14: Rendering List in Lightning Web Component

In this chapter, we will go through rendering list in Lightning web Component i.e. how we can loop over component markup.

Topics Covered: 

  • What is loop
  • for:each and iterator directives
  • Advantage of iterator
  • Understanding code line by line

What is Loop

Lets understand, what is loop-  Loops allow you to do a task over and over again.

As you would have learned in Apex that it uses three types of loops.

  • while
  • do-while
  • for

Below is a simple example of a for loop in apex

List <String> fit = new List<String>{'Gym', 'Crossfit', 'Yoga'};
for(String f : fit){
    System.debug('We have ' + f);
}

When you run the code then you will see:  Gym, Crossfit, Yoga.

The same concept of loop applies in LWC

How to iterate over multiple items in LWC

To iterate over list we can use two directives

  1. for:each 
  2. Iterator

Use of Key 

Whenever we use for:each or Iterator we need to use key directive on the element on which we are doing iteration. Key gives unique id to each item. Remember, without key we cannot do iteration.

When a list changes, the framework uses the key to rerender only the item that changed. It is used for performance optimization and isn’t reflected in the DOM at run time.

Confused? don’t worry, we will understand with the help of example.

app.html

<template>
    <lightning-card title="HelloForEach" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
          <lightning-input type="checkbox" label="Show List of CEO" onchange={handleChange}></lightning-input>

            <template if:true={areDetailsVisible} for:each={ceoList} for:item="ceo">
            
               <div key={ceo.Id} class="slds-box">
                   <div class="slds-grid slds-gutters">
                    <div class="slds-col slds-size_1-of-3">   
                   <span>{ceo.Name}</span>
                   </div>
                   <div class="slds-col slds-size_1-of-3">   
                   <span>{ceo.Company}</span>
                   </div>

                </div>
              </div>
            </template>
        </div>
    </lightning-card>
</template>

app.js

// helloForEach.js
import { LightningElement } from 'lwc';

export default class HelloForEach extends LightningElement {
    areDetailsVisible = false;

     handleChange(event) {
        this.areDetailsVisible = event.target.checked;
    }
    ceoList = [
          {
            Id: 1,
            Name: 'Marc Benioff',
            Company: 'Salesforce.com',
        },
        {
            Id: 2,
            Name: 'Sundar Pichai',
            Company: 'Google',
        },
      
        {
            Id: 3,
            Name: 'Elon Musk',
            Company: 'Telsa',
        },
    ];
}

app.css

p {
    font-weight:bolder;
    font-size:30px;
     display: flex;
  justify-content: center;
  align-items: center;

}

Understanding Code Line by Line in JS

ceoList =[]

Declare a ceoList propery which should be an array and it will hold information about different CEO’s

Understanding Code Line by Line in HTML

for:each={ceoList}

User for: each directive and put the property name “ceoList” inside it. We use for: each inside the template

for:item=”ceo”

From the array we want to access current item so use for:item and give it any name. I have given”ceo”. This holds the current element when the iteration will happen. It is similar to for:each loop where you declare variable from the list.

div key={ceo.Id} 

Now we want to show the values so I have created div tag for it. To access current element we need to use the item which holds the current  value within the curly braces so we put {ceo}

Also, the first nested element of the for:each directive should have unique key which will come from the list we created. I have assigned Id as a key here. Therefore put as {ceo.id}

Iterator

Now we will learn how to iterate over items using iterator directive. By iterator you can learn which is first and last element.

Properties of Iterator:

  • value: items in the list
  • index: index of item in the list
  • first: boolean indicating first item in the collection
  • last: boolean indicating last item in the collection

app.html

<template>
    <lightning-card title="HelloIterator" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">
            <template iterator:it={contacts}>
                <li key={it.value.Id}>
                    <div if:true={it.first} class="list-first"></div>
                    {it.value.Name}, {it.value.Title}
                    <div if:true={it.last} class="list-last"></div>
                </li>
            </template>
        </ul>
    </lightning-card>
</template>

app.css

   .list-first {
    border-top: 1px solid black;
    padding-top: 5px;
}

.list-last {
    border-bottom: 1px solid black;
    padding-bottom: 5px;
}

app.js

import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    contacts = [
        {
            Id: 1,
            Name: 'Amy Taylor',
            Title: 'VP of Engineering',
        },
        {
            Id: 2,
            Name: 'Michael Jones',
            Title: 'VP of Sales',
        },
        {
            Id: 3,
            Name: 'Jennifer Wu',
            Title: 'CEO',
        },
    ];
}

.list-first{
border-bottom:1 px solid black;
padding-bottom: 5px;
background-color:blue;
}
.list-last{
    border-bottom:1 px solid black;
    padding-bottom: 5px;
    background-color:red;
    }

 

Understand Code Line by Line in JavaScript

contacts=[]

Declare contacts property which should be an array and it will hold information about different contacts

Understand Code Line by Line in HTML

<template iterator:it={contacts}> :

iterator: to use iterator directive we use iterator

it: in the iterator, each value you want to represent as what variable or name. You can give any name eg: iterator:con

contact: collection name. This is the property which you have created in javascript

In short, we are using iterator directive and it is accepting property “contacts” and within this we want to display all the contacts.

<li key={it.value.Id}>

key: to uniquely identify we must use key.

value: value you want to display.

In short, I used unordered list and then I used a key to display the first nested element. Since we have used iterator, we need to use attribute after the iterator. “it.value” will hold the contact information so we are giving it to key.

Advantage of Iterator over for:each

Iterator has some advantages over for:each because in iterator we can identify first and last element.

div if:true={it.first} class=”list-first”

div if:true : to check if it is my first element.

it.first:To display first element we are using it.first. first is the boolean indicating first item in the collection.

Basically, if we are inside first property then what action I am going to take.

div if:true={it.last} class=”list-last”

div if:true : to check if it is my last element.

it.last: To display last element we are using it.last. last is the boolean indicating last item in the collection.

Conclusion: We can loop using for: each or iterator directives in lwc. Using iterator we can have control over first and last element.

Together we can learn faster !

Join LWC study group on Telegram 

Subscribe to Youtube channel and blog to get latest updates

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes