ApexSensei

Template looping

Repeat markup with for:each or iterator, and put a unique key on the first element in the loop.

for:each

for:each={rows} walks the array. for:item="row" names the current item. Put the directive on a nested <template> around the markup you want to repeat.

The first element inside that template needs key={row.id}. The key is a string or a number. It cannot be the object, and it cannot be the loop index.

iterator

iterator:row={rows} is the other loop. row.value is the item, row.index is the position, and row.first and row.last tell you the ends of the list.

Use iterator when the first or last row needs different markup. It still requires key on the first element inside the template.

Why the key exists

When the array changes, the framework uses the key to update only the row that changed. The key is not written into the live DOM as an attribute.

Give each row a stable id from the data. Generating a new key on every render makes the framework treat every row as new.

Example

html

<template>
  <template for:each={rows} for:item="row">
    <p key={row.id}>{row.label}</p>
  </template>
  <template iterator:row={rows}>
    <p key={row.value.id}>{row.value.label}</p>
  </template>
</template>