Conditions and lists in Lit
Learn Lit conditional rendering with live examples: ternaries and nothing, when, choose and cache, then lists with map, range, join and keyed repeat.
- 01Show and hide parts of a templateUse a ternary with
nothing, anifin a helper method,when(), orchoose(), and know why&&can print false. - 02Render lists from any dataTurn arrays and other iterables into rows with
map, a loop,range(), andjoin(). - 03Pick map or repeatKnow why a typed value stays in the wrong row after a sort. Keep it with its item using
repeat()and a real key, and keep a hidden view withcache().
What are conditions and lists in Lit?
Asha's menu for Leaf and Kettle is online. Now it must list every tea, and mark the ones that are sold out. Ravi has used tools with special words for this in their HTML. "Where are Lit's if and for?"
How do you show a part of a Lit template only sometimes? And how do you draw one row for each tea?
Lit has no special words for either. A condition is plain JavaScript inside ${}: a ternary that gives a template or nothing. A list is an array of templates in one ${}, often made with map(). For rows that must follow their items, Lit adds repeat() with a key.
Here is Asha's menu, with a condition and a list:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-menu.js"; const menu = document.querySelector("tea-menu"); await menu.updateComplete; const root = menu.shadowRoot; console.log(`Rows: ${root.querySelectorAll("li").length}. Sold out: ${root.querySelectorAll("em").length}`);</script>- Lines 1 to 3 are the import map from lesson 20.1. The name
litmeans Lit 3.3.3, from esm.sh. - Line 4 is the menu. Line 6 loads the tea-menu.js tab.
- Line 8 waits for the first render. Line 10 counts the rows and the sold out notes.
The tea-menu.js tab holds the component:
import { LitElement, html, nothing } from "lit";
class TeaMenu extends LitElement {
static properties = { teas: { state: true } };
constructor() {
super();
this.teas = [
{ name: "Sencha", soldOut: false },
{ name: "Gyokuro", soldOut: true },
{ name: "Assam", soldOut: false },
];
}
render() {
return html`<ul>
${this.teas.map((tea) => html`<li>
${tea.name}
${tea.soldOut ? html`<em>sold out</em>` : nothing}
</li>`)}
</ul>`;
}
}
customElements.define("tea-menu", TeaMenu);- Line 4 makes
teasinternal state, as in lesson 20.2. Lines 8 to 12 fill it with three teas. - Line 17 is the list. The array's
map()calls the arrow function once per tea. Each call gives back one small template, a row. - Line 18 writes the tea's name in the row.
- Line 19 is the condition. A sold-out tea gets an
<em>. Any other tea getsnothing, Lit's value for "render no node here".
The menu shows Sencha, Gyokuro sold out, and Assam. The console prints Rows: 3. Sold out: 1.
Each morning, Ravi copies the list of teas onto the shop's chalkboard, one line per tea. Next to a sold-out tea, he adds a small note. Next to the others, he writes nothing at all.
- In real life: The list of today's teas
- In JavaScript: The teas array
- In real life: Writing one line per tea
- In JavaScript: map() making one template per tea
- In real life: The small Sold out note
- In JavaScript: The template the ternary picks
- In real life: Leaving the space blank
- In JavaScript: nothing
Conditions and loops in Lit are plain JavaScript inside ${}. A condition gives a template or nothing. A list gives an array of templates. Lit reuses list rows by their place, unless repeat() gives each row a key.
Lesson 20.3 showed that a child expression takes templates, arrays, and nothing. This lesson puts those three to work.
How do you conditionally render in Lit?
Lit's docs say it plainly: you use JavaScript's own tools (Lit). There are three common ways.
A ternary inside the template
The overview used it on line 19 of tea-menu.js. A ternary is a ? b : c: if a is true, the value is b, else c (the ternary operator). It fits inside ${}, because it's one expression with one value.
For "show this or show nothing", put nothing in the second branch. When a value might be missing, ${this.note ?? nothing} does the same in one step, as Lit's docs show (Lit).
An if statement in a helper method
An if statement can't go inside ${}, because it isn't an expression. So work out the value first, outside the template. A helper method is a small method of the component that returns a piece of the template. Lit's docs show both a variable set by an if in render(), and a method like this one (Lit):
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha" cups="2"></tea-menu-item><tea-menu-item name="Gyokuro" sold-out></tea-menu-item><tea-menu-item name="Assam"></tea-menu-item><script type="module"> import "./tea-menu-item.js"; for (const item of document.querySelectorAll("tea-menu-item")) { await item.updateComplete; console.log(`${item.name}: "${item.shadowRoot.querySelector("p").textContent}"`); }</script>import { LitElement, html, nothing } from "lit";
class TeaMenuItem extends LitElement {
static properties = {
name: {},
cups: { type: Number },
soldOut: { type: Boolean, attribute: "sold-out" },
};
statusTemplate() {
if (this.soldOut) return html`<em>Sold out today</em>`;
if (this.cups > 0) return html`${this.cups} in your cart`;
return nothing;
}
render() {
return html`<h3>${this.name}</h3>
<p>${this.statusTemplate()}</p>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Lines 4 to 6 of the page are three items. Sencha has 2 cups, Gyokuro is sold out, and Assam has neither.
- In the tea-menu-item.js tab, lines 10 to 14 are the helper method. Line 11 returns a template for a sold-out tea. Line 12 returns one for a tea with cups. Line 13 returns
nothingfor the rest. - Line 18 calls the method inside the template. Its result is the paragraph's content.
It prints Sencha: "2 in your cart", Gyokuro: "Sold out today", and Assam: "".
Why it matters: three or more cases read badly as ternaries inside ternaries. A method with plain if statements reads top to bottom, and it keeps render() short.
Each call to render() runs these conditions again. Lit then compares the result with what it drew last time. If the same template comes back, Lit only writes its changed values. If a different template comes back, Lit builds new elements for it. The cache section shows what that costs.
Why does a Lit template show the word false?
Many people learn {soldOut && <em>Sold out</em>} in React (conditional rendering in React). In Lit, the same idea goes wrong. This page tries it next to a ternary:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p id="and"></p><p id="ternary"></p><script type="module"> import { html, nothing, render } from "lit"; const soldOut = false; render(html`Sencha ${soldOut && html`<em>sold out</em>`}`, document.querySelector("#and")); render(html`Sencha ${soldOut ? html`<em>sold out</em>` : nothing}`, document.querySelector("#ternary")); for (const p of document.querySelectorAll("p")) console.log(`${p.id}: "${p.textContent}"`);</script>- Line 8: Sencha is not sold out, so
soldOutisfalse. - Line 9 renders the note with
&&. Line 10 renders it with a ternary andnothing. - Line 11 prints each paragraph's text.
It prints and: "Sencha false" and ternary: "Sencha ". The first paragraph really shows the word false.
Here is why. a && b doesn't give back true or false. When a is falsy, it gives back a itself (what && and || return). So the value in ${} is false. Lit's docs say a boolean in a child expression renders as the text true or false (Lit). React treats false as a hole and draws nothing there (React). Lit writes it.
&&, the expression's value is false, and Lit writes it as text. With a ternary, the value is nothing, and Lit writes no node at all.The shop door has a hook for a sign. On sold-out days, Ravi hangs the Sold out sign. On other days he leaves the hook empty. A new helper is told "hang the sign if it's sold out". On a normal day, he hangs a card that says false.
- In real life: The hook on the door
- In JavaScript: The ${} spot in the template
- In real life: The Sold out sign
- In JavaScript: The template for the note
- In real life: Leaving the hook empty
- In JavaScript: nothing: no node at all
- In real life: A card that says false
- In JavaScript: The value false, written as text
Lit's source shows the two paths. In ChildPart's _$setValue at lit 3.3.3:
- Line 1462 checks for
nothing,null,undefined, and"". For these four, Lit clears the spot and writes no node (lit-html.ts, line 1462). - Lines 1475 and 1476 send every other plain value to
_commitText(), which writes it as text (lines 1475 to 1476).falseis one of them.
Read each row across: the value in ${}, and what Lit renders for it.
| The value in ${} | What Lit renders |
|---|---|
false | The text false. |
true | The text true. |
0 | The text 0. |
"", null, undefined, or nothing | No node at all. |
soldOut && html… when soldOut is false | The text false, because && hands back false. |
cups && html… when cups is 0 | The text 0, because && hands back 0. |
A count has the same trap. With cups at 0, ${cups && html`…`} shows the digit 0. Exercise 1 tries it. The fix is the same: a ternary with nothing, or when(), coming next.
What does Lit's cache directive do?
A condition often switches between two whole views. Think of an order with a details view and a short summary. Lit treats the two branches as two different templates.
When the template in a spot changes, Lit doesn't edit the old elements. It builds the new template's elements and removes the old ones. The source shows it. If the same template comes back, Lit only updates its values (lit-html.ts, lines 1631 to 1641). Otherwise it makes a new copy (lines 1642 to 1668).
Most of the time, that's fine. But a removed view loses everything a person typed in it. Switch the view and see:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><button id="switch">Switch view</button><div id="order"></div><script type="module"> import { html, render } from "lit"; import { cache } from "lit/directives/cache.js"; const order = document.querySelector("#order"); const details = () => html`<label>Note for the kitchen <input></label>`; const summary = () => html`<p>Sencha, 2 cups</p>`; let open = true; const draw = () => render(html`${open ? details() : summary()}`, order); draw(); const first = order.querySelector("input"); document.querySelector("#switch").addEventListener("click", () => { open = !open; draw(); const box = order.querySelector("input"); if (open) console.log(`Same box: ${box === first}. Note: "${box.value}"`); });</script>Type a note, then press Switch view twice. It prints Same box: false. Note: "". Lit threw the old box away and made a new, empty one.
- Line 10 is the details view, with a note box. Line 11 is the summary.
- Line 13 draws one view or the other. Your choice adds cache() around the ternary, or leaves it out.
- Line 15 keeps the first note box. Lines 16 to 21 switch the view on each press, and print when the details are back.
Without cache(), it prints Same box: false. Note: "". With cache(), it prints Same box: true. Note: "less sugar", with the note you typed.
The cache() directive keeps the DOM of a template that isn't showing (Lit). A directive is a function that changes how one expression renders. When the template changes, cache() moves the old view's elements out of the page (cache.ts, lines 63 to 77). When that template comes back, it moves them back in (lines 81 to 95). It files each view under its template's strings, in a WeakMap (line 41).
While hidden, the view waits in a document fragment: a lightweight container for nodes that isn't part of the page. Check the hidden box while the summary shows. Its isConnected is false, and its getRootNode() is a #document-fragment.
cache(), Lit removes the old view's DOM and later builds it again, empty. With cache(), the old view waits in a document fragment, outside the page, and comes back as it was.When it rains, Leaf and Kettle moves its tables inside. One shop throws the patio chairs away and buys new ones on the next sunny day. Asha stacks them in the shed instead, cushions and all, and carries them back out.
- In real life: The patio chairs and their cushions
- In JavaScript: The details view's elements, typed text and all
- In real life: The shed
- In JavaScript: The document fragment
- In real life: Throwing the chairs away each night
- In JavaScript: A switch without cache()
- In real life: Carrying them back out
- In JavaScript: cache() putting the old DOM back
Lit's docs suggest cache() for switching often between large, complicated templates. For most conditions, they say plain JavaScript is all you need (Lit). The playground shows a second use: keeping what someone typed. Directives such as keyed() and guard() come in their own lesson later in the stage.
How do when() and choose() work in Lit?
Lit ships two small helpers for conditions, when() and choose(). Each lives in its own module, so a page only loads the helpers it imports (Lit).
when() picks one of two functions
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><p id="sign"></p><script type="module"> import { html, render } from "lit"; import { when } from "lit/directives/when.js"; const sign = document.querySelector("#sign"); for (const open of [true, false]) { render(html`Leaf and Kettle is ${when(open, () => html`<b>open</b>`, () => html`<i>closed</i>`)}`, sign); console.log(sign.textContent); }</script>- Line 2 maps the folder
lit/too, solit/directives/when.jsresolves. Line 7 importswhen. - Line 9 tries both values of open.
- Line 10 gives
when()three things: the condition, a function for true, and a function for false.
It prints Leaf and Kettle is open, then Leaf and Kettle is closed.
Lit's docs call when() a wrapper around a ternary (Lit). Its false branch is optional. Leave it out, and a false condition renders nothing:
${when(this.soldOut, () => html`<em>Sold out today</em>`)}That makes when() a safe swap for the && trap. With soldOut false, the spot stays empty.
Why does when() take functions?
Here is an easy slip to make with when(). It passes templates, not functions:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><p id="sign"></p><script type="module"> import { html, render } from "lit"; import { when } from "lit/directives/when.js"; const open = true; render(html`Leaf and Kettle is ${when(open, html`<b>open</b>`, html`<i>closed</i>`)}`, document.querySelector("#sign"));</script>Line 8 sets open to true. Line 9 passes two templates, with no () => before them. The page shows Leaf and Kettle is, and nothing more. The console shows a TypeError: something is not a function. The name in it is short and odd, because Lit's normal build is minified: its names are shortened. Lit's development build names it: TypeError: trueCase is not a function.
The body of when() is one line. It calls the branch it picks, like trueCase(condition) (when.ts, line 46). A template is an object, so calling it throws.
Why functions? JavaScript works out every argument before it calls a function. If when() took templates, both would be built on every render, and one thrown away. With functions, only the chosen branch runs.
Ravi hands the kitchen two recipe cards: one for a hot day, one for a cold day. The cook checks the weather and makes only one dish. If Ravi carried in two cooked dishes instead, the kitchen would have nothing to cook.
- In real life: A recipe card
- In JavaScript: A function like () => html
<b>open</b> - In real life: A cooked dish
- In JavaScript: A template made before the choice
- In real life: The kitchen cooking from one card
- In JavaScript: when() calling only the branch it picks
choose() picks one of many cases
For more than two cases, there is choose(value, cases, defaultCase). Lit's docs compare it to a switch statement that is an expression, with no fall-through (Lit). Here it picks the water for each kind of tea:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><ul id="water"></ul><script type="module"> import { html, render } from "lit"; import { choose } from "lit/directives/choose.js"; const teas = [{ name: "Sencha", kind: "green" }, { name: "Assam", kind: "black" }, { name: "Rooibos", kind: "herbal" }]; const heat = (kind) => choose(kind, [ ["green", () => "80 °C"], ["black", () => "95 °C"], ], () => "ask Ravi"); render(teas.map((tea) => html`<li>${tea.name}: ${heat(tea.kind)}</li>`), document.querySelector("#water")); for (const row of document.querySelectorAll("li")) console.log(row.textContent);</script>- Line 8 is three teas, each with a kind.
- Lines 9 to 12 are
heat(). Lines 10 and 11 are the cases: a value, and a function to call for it. Line 12 is the default, for any other kind. - Line 13 renders one row per tea. Line 14 prints each row.
It prints Sencha: 80 °C, Assam: 95 °C, and Rooibos: ask Ravi.
choose() walks the cases in order. It compares with === and calls the first match's function (choose.ts, lines 37 to 43). With no match, it calls the default, if there is one (line 44). With no match and no default, it gives back undefined, which renders nothing. Because it uses ===, the string "4" never matches the number 4, as in a switch statement.
How do you render a list in Lit?
Put an array in a child expression, and Lit renders every item in it (Lit). So any array method that gives back an array of templates makes a list. Here the menu keeps only the cheap teas:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><ul id="menu"></ul><script type="module"> import { html, render } from "lit"; const teas = [ { name: "Sencha", price: 4 }, { name: "Assam", price: 3 }, { name: "Gyokuro", price: 9 }, ]; const cheap = teas.filter((tea) => tea.price < 5); render(html`${cheap.map((tea) => html`<li>${tea.name}, ${tea.price} EUR</li>`)}`, document.querySelector("#menu")); console.log(`Rows: ${document.querySelectorAll("li").length}`);</script>- Lines 7 to 11 are three teas with prices.
- Line 12 keeps the teas under 5 EUR with
filter(). - Line 13 turns each one into an
<li>template withmap(), and renders the array.
The list shows Sencha, 4 EUR and Assam, 3 EUR. The console prints Rows: 2.
A loop works too. Lit's docs build an array with a for...of loop, then put it in the template (Lit). Here is the overview's render() written that way, skipping sold-out teas:
render() {
const rows = [];
for (const tea of this.teas) {
if (tea.soldOut) continue;
rows.push(html`<li>${tea.name}</li>`);
}
return html`<ul>${rows}</ul>`;
}Line 2 starts an empty array. Lines 3 to 6 loop over the teas. Line 4 skips a sold-out tea, and line 5 adds a row for the rest. Line 7 puts the array in the template. Put it in place of lines 15 to 22 of the overview's tab, and the console prints Rows: 2. Sold out: 0.
map(), range(), and join() from Lit
Lit also has small list helpers, each in its own module. Its map() works on any iterable: anything a for...of loop can walk, like a Set (Lit). range() counts numbers, and join() puts a separator between items (Lit, Lit).
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><p id="favourites"></p><p id="strength"></p><p id="steeps"></p><script type="module"> import { html, render } from "lit"; import { map } from "lit/directives/map.js"; import { range } from "lit/directives/range.js"; import { join } from "lit/directives/join.js"; const favourites = new Set(["Sencha", "Assam"]); render(join(map(favourites, (name) => html`<b>${name}</b>`), " and "), document.querySelector("#favourites")); render(map(range(3), () => "●"), document.querySelector("#strength")); render(join(map(range(1, 4), (n) => `${n} min`), ", "), document.querySelector("#steeps")); for (const p of document.querySelectorAll("p")) console.log(p.textContent);</script>- Lines 9 to 11 import the three helpers. Line 12 is a Set of favourite teas.
- Line 13 maps the Set to bold names, and
join()puts " and " between them. - Line 14 draws one dot for each number of
range(3): 0, 1, and 2. - Line 15 counts from 1 up to 4, but stops before 4, and joins the steep times with commas.
It prints Sencha and Assam, ●●●, and 1 min, 2 min, 3 min.
join() works like beads on a string, with a spacer between each two beads. range() takes up to three numbers: a start, an end it never reaches, and a step.
Lit's map() is a generator function: it hands back its results one at a time (generators). Its loop yields one result per item (map.ts, line 30). range() and join() are generators too (range.ts, lines 29 to 35, join.ts, lines 28 to 40). Lit reads their items one by one as it renders. Lit's cheat sheet suggests the array's map() for arrays, and Lit's map() for other iterables (Lit).
Why does a typed value stay in the wrong row?
Ravi wants a box in each row for the steep time, in minutes. He also wants to sort the teas by price. He types 5 in Assam's box and presses Sort by price. Try it with each choice:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><ol id="list"></ol><button id="sort">Sort by price</button><script type="module"> import { html, render } from "lit"; import { repeat } from "lit/directives/repeat.js"; let teas = [ { id: 1, name: "Sencha", price: 4 }, { id: 2, name: "Assam", price: 3 }, { id: 3, name: "Gyokuro", price: 9 }, ]; const row = (tea) => html`<li>${tea.name}, ${tea.price} EUR <input aria-label="Minutes for ${tea.name}" size="2"> min</li>`; const draw = () => render(teas.map(row), document.querySelector("#list")); draw(); document.querySelector("#sort").addEventListener("click", () => { teas = teas.toSorted((a, b) => a.price - b.price); draw(); for (const box of document.querySelectorAll("input")) { if (box.value) console.log(`${box.getAttribute("aria-label")}: ${box.value}`); } });</script>Type 5 in Assam's box, then press Sort by price. It prints Minutes for Sencha: 5. Assam moved to row 1, but your 5 stayed in row 2, which is Sencha's now.
- Lines 9 to 13 are the teas. Each has an id, a name, and a price.
- Line 14 is one row: the name, the price, and a box. The box's label comes from an expression. Its value doesn't: no expression writes it.
- Line 15 draws the list. Your choice changes only this line.
- Line 18 sorts a copy of the teas with
toSorted(), which leaves the old array as it was (copying methods). Lines 20 to 22 print which box holds a value.
With map(), it prints Minutes for Sencha: 5. Assam moved to row 1, but your 5 stayed in row 2, next to Sencha. With repeat() by id, it prints Minutes for Assam: 5. With repeat() by index, it prints Minutes for Sencha: 5 again.
Look at the map() choice again. The label of row 2 changed to Minutes for Sencha, because an expression writes it. The 5 didn't move, because nothing writes it. Lit filled the same three rows with the new order.
map(), Lit fills each row by its place. Row 2 gets Sencha's name and price, because Sencha is second now. The box keeps the 5, because no expression writes its value.Leaf and Kettle hosts a tasting. One host seats guests by chair number: the second guest in the queue takes chair 2. Assam's guest leaves a coat on chair 2 and steps out. When the queue changes, Sencha's guest sits by the coat. Another host puts a name card on each seat, so every guest finds their own chair, coat and all.
- In real life: The chairs, in a row
- In JavaScript: The rows Lit already made
- In real life: A coat left on chair 2
- In JavaScript: The 5 typed into row 2's box
- In real life: Seating by chair number
- In JavaScript: map(): item 2 gets row 2
- In real life: Seating by name card
- In JavaScript: repeat() with a key: each item gets its own row
Your own renderer did the same in lesson 18.3. Lit's comes from _commitIterable(), the code that renders an array or another iterable. This is its loop, as it is in Lit's source:
for (const item of value) {
if (partIndex === itemParts.length) {
// If no existing part, create a new one
// TODO (justinfagnani): test perf impact of always creating two parts
// instead of sharing parts between nodes
// https://github.com/lit/lit/issues/1266
itemParts.push(
(itemPart = new ChildPart(
this._insert(createMarker()),
this._insert(createMarker()),
this,
this.options
))
);
} else {
// Reuse an existing part
itemPart = itemParts[partIndex];
}
itemPart._$setValue(item);
partIndex++;
}In plain words, line by line:
- Line 1 walks the items.
partIndexcounts them: 0, 1, 2. - Lines 2 to 14: if there is no part for this place yet, make one. A part is Lit's object for one spot in the page, here one row.
- Lines 15 to 18: otherwise, take the part already at this place.
- Line 19 gives that part the item's value. Line 20 moves to the next place.
The only thing that picks a row is partIndex, the item's place. Nothing asks which tea the row showed before. So the item at place 2 updates the row at place 2 (the whole method, lines 1681 to 1734). Lit's docs say the same: a list from map() keeps its DOM nodes and gives them new values (Lit).
Why it matters: anything the template doesn't write stays with the row. That's typed text, a ticked box, or the state inside a custom element.
How does repeat() keep each row with its item?
repeat() takes three things: the items, a key function, and a template function (Lit). A key is a value that names one item for good, like a tea's id.
repeat(
teas,
(tea) => tea.id,
(tea) => html`<li>${tea.name}, ${tea.price} EUR <input aria-label="Minutes for ${tea.name}" size="2"> min</li>`,
)- Line 2 is the items.
- Line 3 is the key function. It gets each tea and returns its id.
- Line 4 is the template for one tea, the same row as before.
Lit's docs say that with a key function, repeat() keeps each key with its DOM, and moves the DOM when the order changes. That's the second playground choice: Assam's row stayed Assam's, with its 5.
repeat() and the tea's id as the key, each row belongs to one tea. After the sort, Lit puts the rows in the new order, and Assam's row still holds the 5.The key must be unique. Lit's docs ask for "a guaranteed unique key" for each item (Lit). An id from your data is the usual choice.
Why doesn't the index work as a key?
The third playground choice used (tea, index) => index. It printed the same line as map(). The index is the item's place, counted from 0. So after a sort, row 2 still has the key 1, whichever tea is in it. Each key finds the row at the same place.
Lit's tutorial says it directly: with no key function, or one that returns the index, repeat() acts like map() (Lit). The source shows why: with no key function, the key is the index (repeat.ts, line 56). Lesson 18.3 found the same with its own repeat().
One more rule: repeat() only works in a child expression. In an attribute, it throws repeat() can only be used in text expressions (repeat.ts, line 37).
When should you use map or repeat in Lit?
Lit's docs give two reasons to use repeat() (Lit):
- Updating the rows costs more than moving them.
- The rows hold state that no template expression controls, like a typed value or a ticked box.
Otherwise, they say, use map or a loop. They also call map() "smaller and faster" than repeat() (Lit). This page shows the first reason. It sorts the same three teas both ways, and counts the changes in the page:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><ol id="by-place"></ol><ol id="by-id"></ol><script type="module"> import { html, render } from "lit"; import { repeat } from "lit/directives/repeat.js"; const teas = [{ id: 1, name: "Sencha", price: 4 }, { id: 2, name: "Assam", price: 3 }, { id: 3, name: "Gyokuro", price: 9 }]; const sorted = teas.toSorted((a, b) => a.price - b.price); const row = (tea) => html`<li>${tea.name}, ${tea.price} EUR</li>`; function sortAndWatch(list, before, after) { render(before, list); const watcher = new MutationObserver(() => {}); watcher.observe(list, { subtree: true, childList: true, characterData: true }); render(after, list); const changes = watcher.takeRecords(); const texts = changes.filter((change) => change.type === "characterData").length; const moved = new Set(changes.flatMap((change) => [...change.addedNodes]).filter((node) => node.localName === "li")); return `texts changed: ${texts}, rows moved: ${moved.size}`; } console.log(`map: ${sortAndWatch(document.querySelector("#by-place"), teas.map(row), sorted.map(row))}`); console.log(`repeat: ${sortAndWatch(document.querySelector("#by-id"), repeat(teas, (tea) => tea.id, row), repeat(sorted, (tea) => tea.id, row))}`);</script>- Line 9 is the teas. Line 10 is a sorted copy. Line 11 is one row, with no box this time.
- Lines 12 to 21 render the first list, then the second. A
MutationObserveris a browser object that records changes to the DOM. Here it lists each change Lit makes in between. - Line 18 counts changed texts. Line 19 counts rows that were moved.
- Line 22 tries map(). Line 23 tries repeat() with the id.
It prints map: texts changed: 4, rows moved: 0 and repeat: texts changed: 0, rows moved: 1.
map() rewrote the name and price in rows 1 and 2. repeat() moved one row and wrote no text. With rows this small, either is quick. With rows full of elements, moving one costs less than rewriting all of them.
Read each row across: what you write, how Lit matches rows, what happens to typed text, and when to use it.
| What you write | How Lit matches rows to items | A typed value, after a sort | Use it when |
|---|---|---|---|
teas.map(row), a loop, or map(teas, row) | By position. Row 1 gets the first item, row 2 the second. | It stays in its row, next to a different tea. | The template writes everything a row shows. It's the smaller and faster choice. |
repeat(teas, (tea) => tea.id, row) | By key. Each tea keeps its own row, and Lit moves the row. | It moves with its tea. | Rows hold state no expression controls, or moving a row costs less than updating it. |
repeat(teas, (tea, index) => index, row), or repeat() with no key | By position, like map(). | It stays in its row, like map(). | Never on purpose. Use map() instead. |
What about very long lists?
For lists too long to render at once, Lit's cheat sheet points to the Lit Virtualizer (Lit). It draws only the rows near the view, and it's a Lit Labs package, so it may still change. On npm it's @lit-labs/virtualizer, version 2.1.1 (npm). Lesson 18.3 runs it on 10,000 teas.
Building a sortable tea menu with conditions and lists
Asha's real menu puts it all together. Filter buttons pick a kind of tea. A button sorts by price. Each row shows the price with the kit's tea-price, the water heat, and a minutes box.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-kit/tea-price.js"; import "./tea-menu.js";</script>import { LitElement, html } from "lit";
import { choose } from "lit/directives/choose.js";
import { map } from "lit/directives/map.js";
import { repeat } from "lit/directives/repeat.js";
import { when } from "lit/directives/when.js";
export class TeaMenu extends LitElement {
static properties = { teas: { state: true }, kind: { state: true } };
constructor() {
super();
this.kind = "all";
this.teas = [
{ id: 1, name: "Sencha", kind: "green", price: 4 },
{ id: 2, name: "Assam", kind: "black", price: 3 },
{ id: 3, name: "Gyokuro", kind: "green", price: 9, soldOut: true },
];
}
row(tea) {
return html`<li>
${tea.name}, <tea-price .amount=${tea.price} currency="EUR"></tea-price>,
${choose(tea.kind, [["green", () => "80 °C"], ["black", () => "95 °C"]], () => "ask Ravi")}
${tea.soldOut ? html`<em>sold out</em>` : html`<input aria-label="Minutes for ${tea.name}" size="2"> min`}
</li>`;
}
render() {
const shown = this.teas.filter((tea) => this.kind === "all" || tea.kind === this.kind);
return html`${map(["all", "green", "black", "oolong"], (kind) => html`
<button aria-pressed=${this.kind === kind} @click=${() => (this.kind = kind)}>${kind}</button>`)}
<button @click=${() => (this.teas = this.teas.toSorted((a, b) => a.price - b.price))}>Sort by price</button>
${when(shown.length > 0,
() => html`<ol>${repeat(shown, (tea) => tea.id, (tea) => this.row(tea))}</ol>`,
() => html`<p>No ${this.kind} teas today.</p>`)}`;
}
}
customElements.define("tea-menu", TeaMenu);- Line 6 of the page loads
tea-pricefrom the kit. Line 7 loads the menu. - Lines 20 to 26 are
row(), a helper method. Line 22 sets the price's.amountproperty. Line 23 useschoose()for the water. Line 24 shows sold out, or a minutes box. - Line 29 keeps the teas of the chosen kind.
- Lines 30 and 31 use Lit's
map()to make the four filter buttons.aria-pressedtells a screen reader which one is on. - Line 32 sorts a copy of the teas, so Lit sees a new array and renders again.
- Lines 33 to 35 use
when(): the list if any tea is shown, or a message if none is. Line 34 draws the rows withrepeat(), keyed by id.
Type 5 in Assam's box and press Sort by price. Assam moves to the top with its 5. Press black, and only Assam is left, still with its 5. Press oolong, and the menu says No oolong teas today. Press all, and the 5 is gone.
Why did the 5 go? when() switched from the list template to the message template, so Lit removed the list. Coming back, it built a new one. That's the cache section again, and exercise 6 fixes it.
Line 32 makes a new array on purpose. A sort in place, with sort(), would change the same array, and Lit wouldn't see a change (lesson 20.2). Now sort some lists of your own:
- Tea names and prices that come fresh from the server every minute
- Three strength dots, drawn with
range(3) - A footer of five links that never change order
- Breadcrumb links joined with
join() - A sortable list with a steep minutes box in each row
- A to-do list with checkboxes, sorted by date
- Rows that each hold a running tea-timer element
- A long queue where one order often jumps to the top
Put each list where it belongs: is map() or a loop enough, or does it need repeat() with a key?
Common mix-ups
- "${soldOut && html`…`} renders nothing when soldOut is false." No. It renders the text false. Use a ternary with
nothing, orwhen(). - "Lit needs special words for if and for." No. Ternaries,
ifstatements in methods, and array methods are all plain JavaScript. The directives are small helpers. - "when(open, html`…`) works like a ternary." No.
when()calls its branches, so each must be a function. A template throws a TypeError. - "A sort with map() moves the rows." No. map() keeps the rows in place and writes new values into them. A typed value stays where it was.
- "Any key makes repeat() keyed." No. The index changes when the order does, so repeat() by index acts like map(). Use a value that names the item, like its id.
- "repeat() is always faster than map()." No. Lit's docs call map() smaller and faster. Use repeat() when rows must follow their items.
- "Hiding a view keeps what was typed in it." No. Without
cache(), Lit removes the hidden view's DOM and builds a new one later.
Practice exercises
Read the page without running it. What does the console print?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<p id="cart"></p>
<script type="module">
import { html, render } from "lit";
const cups = 0;
render(html`In cart: ${cups && html`<b>${cups} cups</b>`}`, document.querySelector("#cart"));
console.log(document.querySelector("#cart").textContent);
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><p id="cart"></p><script type="module"> import { html, render } from "lit"; const cups = 0; render(html`In cart: ${cups && html`<b>${cups} cups</b>`}`, document.querySelector("#cart")); console.log(document.querySelector("#cart").textContent);</script>It prints In cart: 0. cups is 0, which is falsy, so && hands back 0 itself. Lit writes the number 0 as text. Write cups > 0 ? html… : nothing instead.
Read the page without running it. What does the console print?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }
</script>
<p id="steeps"></p>
<script type="module">
import { render } from "lit";
import { map } from "lit/directives/map.js";
import { range } from "lit/directives/range.js";
import { join } from "lit/directives/join.js";
render(join(map(range(2, 9, 3), (n) => `${n} min`), ", "), document.querySelector("#steeps"));
console.log(document.querySelector("#steeps").textContent);
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><p id="steeps"></p><script type="module"> import { render } from "lit"; import { map } from "lit/directives/map.js"; import { range } from "lit/directives/range.js"; import { join } from "lit/directives/join.js"; render(join(map(range(2, 9, 3), (n) => `${n} min`), ", "), document.querySelector("#steeps")); console.log(document.querySelector("#steeps").textContent);</script>It prints 2 min, 5 min, 8 min. range() starts at 2, steps by 3, and stops before 9. map() turns each number into text, and join() puts a comma between them.
The sign should say Open until 6 pm, but the page throws. Fix the tea-sign.js tab. What does the console print then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-sign open></tea-sign><script type="module"> import "./tea-sign.js"; const sign = document.querySelector("tea-sign"); await sign.updateComplete; console.log(`Sign: ${sign.shadowRoot.querySelector("p").textContent}`);</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-sign open></tea-sign><script type="module"> import "./tea-sign.js"; const sign = document.querySelector("tea-sign"); await sign.updateComplete; console.log(`Sign: ${sign.shadowRoot.querySelector("p").textContent}`);</script>Only line 8 of the tea-sign.js tab changes: each template becomes a function, () => html…. when() calls the one it picks, so the console prints Sign: Open until 6 pm.
Sencha's paragraph shows the word false. Fix the tea-menu-item.js tab. What does the console print for Sencha then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><tea-menu-item name="Gyokuro" sold-out></tea-menu-item><script type="module"> import "./tea-menu-item.js"; for (const item of document.querySelectorAll("tea-menu-item")) { await item.updateComplete; console.log(`${item.name}: "${item.shadowRoot.querySelector("p").textContent}"`); }</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><tea-menu-item name="Gyokuro" sold-out></tea-menu-item><script type="module"> import "./tea-menu-item.js"; for (const item of document.querySelectorAll("tea-menu-item")) { await item.updateComplete; console.log(`${item.name}: "${item.shadowRoot.querySelector("p").textContent}"`); }</script>Lines 1 and 16 of the tea-menu-item.js tab change. Line 1 imports nothing, and line 16 becomes this.soldOut ? html… : nothing. Now Sencha prints Sencha: "", and Gyokuro still shows its note.
Tick Assam, then press Sort by name. The tick lands on Gyokuro. Fix the tea-tasting.js tab, and try again. What does the console print then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-tasting></tea-tasting><script type="module" src="./tea-tasting.js"></script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-tasting></tea-tasting><script type="module" src="./tea-tasting.js"></script>Only line 24 of the tea-tasting.js tab changes: the key becomes (tea) => tea.id. Each tea now keeps its own label and box, so the tick moves with Assam, and the console prints Ticked: Assam.
This is the practical's menu. Type 5 in Assam's box, press oolong, then press all. The 5 is gone. Fix the tea-menu.js tab, and try again. What does Assam's box hold then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-kit/tea-price.js"; import "./tea-menu.js";</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-kit/tea-price.js"; import "./tea-menu.js";</script>Only the tea-menu.js tab changes. A new line 2 imports cache, and the when() becomes ${cache(when(…))}. While the message shows, cache() keeps the list in a document fragment. Press all, and the same list comes back, with 5 still in Assam's box.
Check your understanding
Question 1 of 8What does the first line of this && page print?
Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <p id="and"></p> <p id="ternary"></p> <script type="module"> import { html, nothing, render } from "lit"; const soldOut = false; render(html`Sencha ${soldOut && html`<em>sold out</em>`}`, document.querySelector("#and")); render(html`Sencha ${soldOut ? html`<em>sold out</em>` : nothing}`, document.querySelector("#ternary")); for (const p of document.querySelectorAll("p")) console.log(`${p.id}: "${p.textContent}"`); </script>Choose an answer to see the explanation.
Question 2 of 8Which values render no node at all in a child expression?
Choose an answer to see the explanation.
Question 3 of 8What happens with
when(open, html<b>open</b>, html<i>closed</i>)when open is true?Choose an answer to see the explanation.
Question 4 of 8
choose("herbal", [["green", () => "80 °C"]])has no default. What does it render?Choose an answer to see the explanation.
Question 5 of 8In this list, you type 5 in Assam's box, then press Sort by price. Which box holds the 5?
Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } } </script> <ol id="list"></ol> <button id="sort">Sort by price</button> <script type="module"> import { html, render } from "lit"; import { repeat } from "lit/directives/repeat.js"; let teas = [ { id: 1, name: "Sencha", price: 4 }, { id: 2, name: "Assam", price: 3 }, { id: 3, name: "Gyokuro", price: 9 }, ]; const row = (tea) => html`<li>${tea.name}, ${tea.price} EUR <input aria-label="Minutes for ${tea.name}" size="2"> min</li>`; const draw = () => render(teas.map(row), document.querySelector("#list")); draw(); document.querySelector("#sort").addEventListener("click", () => { teas = teas.toSorted((a, b) => a.price - b.price); draw(); for (const box of document.querySelectorAll("input")) { if (box.value) console.log(`${box.getAttribute("aria-label")}: ${box.value}`); } }); </script>Choose an answer to see the explanation.
Question 6 of 8What does
repeat(teas, (tea, index) => index, row)do after a sort?Choose an answer to see the explanation.
Question 7 of 8Lit's docs give two reasons to pick repeat() over map(). Which pair is it?
Choose an answer to see the explanation.
Question 8 of 8With
cache(), you type a note in the details view, switch to the summary, and switch back. What comes back?Choose an answer to see the explanation.
Key takeaways
- Conditions and lists in Lit are plain JavaScript inside ${}.
- A ternary with nothing shows a template or no node. An if statement goes in a helper method.
- soldOut && html`…` renders the text false. Lit writes booleans and numbers as text.
- A new template in a spot means new DOM. cache() keeps a hidden template's DOM, typed text and all.
- when() and choose() take functions, and call only the branch they pick.
- A list is an array or iterable of templates: map(), a loop, Lit's map(), range(), and join().
- map() reuses rows by position. repeat() with a unique key, like an id, keeps each row with its item.
- Use repeat() when rows hold state the template doesn't write, or moving beats updating. Otherwise use map().
Remember the one-liner.
map() seats each item by chair number. repeat() seats it by name card. Pick name cards when a seat holds something of its own.
Sources
The facts on this page come from these docs and source files:
- Conditionals, Lit.
- Expressions, Lit.
- Conditional rendering, React.
- lit-html.ts, at lit 3.3.3, Lit.
- Built-in directives, Lit.
- cache.ts, at lit 3.3.3, Lit.
- when.ts, at lit 3.3.3, Lit.
- choose.ts, at lit 3.3.3, Lit.
- Lists, Lit.
- map.ts, at lit 3.3.3, Lit.
- range.ts, at lit 3.3.3, Lit.
- join.ts, at lit 3.3.3, Lit.
- Working with lists, a tutorial, Lit.
- repeat.ts, at lit 3.3.3, Lit.
- The Lit Cheat Sheet, Elliott Marquez, Lit.
- @lit-labs/virtualizer, npm.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Styles in Lit, the next lesson of the Lit stage. It covers static styles, the css tag, sharing styles, and rendering without shadow DOM.