Sub topic 1
Templates, Data Binding, and List Data in LWC
Prerequisites
Assume you know basic HTML and JavaScript arrays, including map. You should also know that an LWC has an HTML template and a JavaScript class extending LightningElement.
Templates, data binding and the shape of list data
An LWC template displays values from the component class through data binding. A property inside curly braces, such as {contact.Name}, reads a value from JavaScript.
A list usually has an array of objects. Each object represents one record and should contain a stable identifier.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
}Rendering an array with `for:each`
Use for:each to repeat markup for every array element. for:item gives the current object a template name.
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>The inner <template> is a loop. During each pass, contact refers to one object from contacts.
Using the current item and `for:index`
Add for:index when the zero-based position matters. The index starts at 0.
<template>
<ul>
<template
for:each={contacts}
for:item="contact"
for:index="position">
<li key={contact.Id} data-position={position}>
{position}: {contact.Name}
</li>
</template>
</ul>
</template>Use the index for display or a data attribute. Do not use it as the key when records can be inserted, removed, or reordered.
Why every item needs a stable key
A key is a unique value that lets LWC track each rendered item. Put key on the first element inside the iteration template. Use a persistent record ID, not an array position.
Keys must be unique among siblings and must not change when the list order changes. Missing, duplicate, or index-based keys can cause warnings and incorrect DOM reuse.
Exercise
What should you use as the key for a list of contacts, and why should you avoid the array index?
Show answer
Use each contact's stable, unique Id. An index changes when items are inserted, removed, or reordered, so it cannot reliably identify the same record.