Overview
ThecompositionIteration component demonstrates how to combine component composition with template iteration. This pattern allows you to:
- Loop through arrays of data using
for:each - Render multiple instances of a child component
- Pass unique data to each component instance
- Use proper keys for list rendering
Parent Component Structure
JavaScript (compositionIteration.js)
Template (compositionIteration.html)
Child Component
This example uses the samecontactTile component from the basics example:
Key Concepts
for:each Directive
Thefor:each directive iterates over an array and renders template content for each item:
for:each={arrayName}- The array to iterate overfor:item="itemName"- Variable name for each itemkey={item.uniqueId}- Required unique key for each iteration
Key Attribute
Every element inside afor:each loop must have a unique key attribute:
- Use a stable, unique identifier (like an Id field)
- Don’t use array index as key
- The key helps the framework optimize rendering
Component Instance Creation
Each iteration creates a new instance of the child component:contactTile instances, each with its own contact data.
Data Flow
- Parent component defines an array of contacts
- Template iterates over the array using
for:each - Each iteration creates a child component instance
- Each child receives its specific contact object via
@apiproperty - Child components render independently with their own data
Usage Patterns
This pattern is ideal for:- Displaying lists of similar items (contacts, products, records)
- Creating dynamic grids or card layouts
- Rendering search results
- Building data tables with custom row components
- Any scenario requiring multiple component instances with different data
Alternative: iterator:it
For more control, you can useiterator:it to access index and first/last properties:
Source Files
- Parent:
force-app/main/default/lwc/compositionIteration/ - Child:
force-app/main/default/lwc/contactTile/
