Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Templates and Directives

Lists and Repeating Templates

Render lists in Lit with Array.map and the repeat directive: understand keys, DOM reuse, reordering with state preserved, empty states, filtering, sorting and when map is enough.

Lists are everywhere: todo items, search results, table rows, menu entries. In Lit you render a list by putting an array of templates in a child expression. The two tools are plain Array.prototype.map and the repeat directive. They look similar, but they differ in how they treat the DOM when the list changes, and that difference shows up as lost input text, broken animations and wasted work. This lesson explains both and tells you which to pick.

Lit renders arrays and iterables

A child expression may hold an array (or any iterable) of templates, strings or numbers. Lit renders each item in order.

Render a list with map

map returns an array of TemplateResults. Each is rendered into its own spot. When the array changes, Lit updates by position: item 0 is compared with the new item 0, item 1 with the new item 1, and so on. If the new list is longer, extra DOM is created; if shorter, extra DOM is removed.

The problem with position-based updates

Position-based reuse is fast and perfectly fine when items are simple text. It goes wrong when each item has state that lives in the DOM: a typed input value, a focus ring, a checked box, an animation in progress. Remove the first item and the DOM nodes for positions 0 to n-2 are reused for different data, so the typed text now sits beside the wrong label.

map reuses DOM by position

Type "a" next to Ada and "g" next to Grace in both lists, then remove the first person. In the map list, Grace's row now shows the note "a": the first input was reused for Grace. In the repeat list, Grace keeps her "g". Using a key told Lit that the DOM for Ada should be removed, not recycled.

flowchart LR
  subgraph map["map: by position"]
    m1["row 0: was Ada, now Grace"]
    m2["row 1: was Grace, now Linus"]
    m3["row 2: removed"]
  end
  subgraph rep["repeat: by key"]
    r1["Ada row removed"]
    r2["Grace row kept"]
    r3["Linus row kept"]
  end

Without keys, rows are recycled by position. With keys, they follow their data.

The repeat directive

repeat(items, keyFunction, template) takes an iterable, a function that returns a unique key per item, and a template function. Lit tracks DOM by key, so when items are added, removed or reordered, the existing DOM nodes move with their data.

JavaScript
import { repeat } from "lit/directives/repeat.js";

html`<ul>${repeat(this.todos, (t) => t.id, (t, index) => html`<li>${t.text}</li>`)}</ul>`

If you pass only two arguments, repeat(items, template), it behaves like map. The key function is what makes it different, and the key must be:

  • Unique within the list. Duplicate keys cause bugs.
  • Stable for the same logical item across renders. An id from your data is perfect.
  • Not the array index, because an index changes when items move, which defeats the purpose.

When to use map and when to use repeat

Situation Use
Static or text-only items, no DOM state map (simpler, a bit faster)
Items with inputs, focus, animations or nested components with state repeat with a stable key
The list reorders or has items removed from the middle repeat
Items only ever append at the end Either, map is enough

A good default: start with map, and switch to repeat when you notice state going to the wrong item or when users can reorder.

Reordering, sorting and filtering

Never sort or reverse the array stored in a property in place. That mutates it, and Lit would not see a change. Make a copy when you derive the view:

Sort and filter a keyed list

The component keeps the master list in a plain field and computes the visible list inside a getter, using filter (which returns a new array) before sort. Calling sort on the result of filter is safe because it is already a copy. Note the empty state: an empty array renders nothing, so show a hint explicitly. In the template, $${p.price} prints a literal dollar sign followed by the value.

Rendering other iterables

Anything iterable works: a Set, a Map.values(), a generator. For numeric ranges, the range() directive generates numbers lazily:

JavaScript
import { range } from "lit/directives/range.js";
html`${map(range(5), (i) => html`<span>${i}</span>`)}`

Here map is a directive from lit/directives/map.js that works on any iterable, unlike Array.prototype.map. Together with join (inserts a separator between items) these small helpers cover most loops without temporary arrays. Built-in Directives lists them all.

Large lists

repeat and map render every item. A list of 10,000 rows creates 10,000 DOM nodes, and no template trick fixes that. For very long lists, use virtualization: the @lit-labs/virtualizer package renders only the rows near the viewport. Pagination and "load more" buttons are the simple alternative and are accessible by default.

Common mistakes

  • Using the array index as the key. Reordering then reuses the wrong DOM.
  • Mutating the array (push, sort, splice) and expecting a re-render. Assign a new array.
  • Using non-unique keys. Two items with the same key make Lit throw away or misplace nodes.
  • Forgetting an empty state, which leaves a blank area.
  • Using repeat everywhere. It has bookkeeping cost, and map is faster for simple lists.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Lit update an array rendered with plain map when an item is removed from the start?

    Without keys, Lit compares item by position, so DOM state such as typed text can end up beside the wrong data.
  2. 2. What makes a good key for repeat?

    Keys must be unique and stable for the same item across renders, which is what an id provides.
  3. 3. Which is correct for sorting a list stored in a reactive property?

    Sorting in place mutates the stored array. Copy first so the original and change detection stay correct.
  4. 4. When is plain map a good choice?

    map is simpler and a bit faster, and position-based reuse is harmless when items carry no DOM state.

Summary

  • Child expressions accept arrays and iterables of templates.
  • map reuses DOM by position; repeat(items, keyFn, template) reuses DOM by key.
  • Use stable unique ids as keys, never indexes.
  • Copy before sorting or filtering; replace arrays instead of mutating them.
  • Show an explicit empty state, and virtualize very long lists.

Next: Built-in Directives