Overview
ThehelloForEach component demonstrates how to iterate over arrays in Lightning Web Components using the for:each directive. This is the most common way to render lists of data in LWC templates.
What It Does
This component displays a list of contacts by iterating over an array of contact objects. Each contact’s name and title are rendered in a list item, demonstrating how to loop through data and access object properties in templates.Component Code
Key Concepts
- for:each Directive: Iterates over an array of items
- for:item: Defines the variable name for the current iteration item
- key Attribute: Required unique identifier for each list item (improves rendering performance)
- Array of Objects: Demonstrates accessing properties of objects within an array
- Template Tag: The
for:eachdirective must be used on a<template>tag
How It Works
- The
contactsarray contains three contact objects - The
for:eachdirective loops through each contact in the array - For each iteration, the current contact is accessible via the
contactvariable - The
keyattribute usescontact.Idto uniquely identify each list item - Each contact’s
NameandTitleproperties are displayed
Important Requirements
- key attribute is mandatory: Every element in a
for:eachloop must have a uniquekey - Use stable identifiers: Keys should be stable and unique (like IDs), not array indices
- Template wrapper: The
for:eachdirective must be on a<template>tag
Usage Example
To use this component in your Salesforce org:When to Use for:each
Usefor:each when:
- You need to render a simple list of items
- You don’t need access to first/last item information
- You want straightforward iteration without additional metadata
