Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Templates and Directives

Conditional Rendering in Lit

Show and hide content in Lit templates with ternaries, logical operators, the nothing value, early returns, the when and choose directives, and learn when to use hidden or CSS instead.

Almost every interface shows different things in different states: a spinner while loading, an error message when something fails, an empty-state hint for a list with no items. Lit has no special if syntax in templates. Instead you use ordinary JavaScript: ternaries, &&, early returns and helper functions. This lesson shows each pattern, the special value nothing, and two directives (when and choose) for readable conditionals.

Because a template is just a JavaScript expression, anything that returns a template (or text, or nothing) can appear in a child position.

The ternary operator

The most common pattern is a ternary inside a child expression:

Ternary: show login or logout

Each branch is its own template. When the condition flips, Lit throws away the old branch's DOM and builds the new one. Switching back and forth rebuilds each time, which is fine for small pieces and something to remember for expensive branches.

Logical AND and the nothing value

A ternary with an empty branch is awkward: cond ? html... : "". Two cleaner choices exist.

The && operator can work because null, undefined and "" render nothing. But false renders the text "false" in Lit, and 0 renders "0". So ${this.error && html

${this.error}

} is safe only when this.error is a string or null. Prefer an explicit ternary with the special value nothing.

JavaScript
import { html, nothing } from "lit";

html`${this.error ? html`<p class="error">${this.error}</p>` : nothing}`

nothing is a sentinel that renders no node at all (not even an empty text node). In attribute position it removes the attribute, which is useful for optional attributes:

JavaScript
html`<a href=${this.url ?? nothing}>Link</a>`

When this.url is undefined, the href attribute is absent entirely, instead of href="". The built-in directive ifDefined does the same job and is covered in Built-in Directives.

nothing removes an attribute

Without a href, the anchor is not a link: it is not underlined or clickable and not in the tab order. After toggling, the attribute exists and the text becomes a real link.

Early return from render

When a whole component changes shape, return early. This reads like normal code and avoids deep nesting.

Loading, error, and data states

Four states, four if lines, one clear read. For bigger components, move each state into its own method (renderLoading(), renderError()), which makes render() a short table of contents.

The when directive

when(condition, trueCase, falseCase) is a readable ternary. Both cases are functions, so only the chosen branch is computed. This matters when a branch is expensive or accesses properties that might not exist.

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

html`${when(
  this.user,
  () => html`<p>Welcome, ${this.user.name}</p>`,
  () => html`<p>Please sign in.</p>`
)}`

If you skip the third argument, the false case renders nothing.

The choose directive

For more than two cases, choose(value, [[case, fn], ...], defaultFn) works like a switch:

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

html`${choose(this.status, [
  ["loading", () => html`<spinner-icon></spinner-icon>`],
  ["error",   () => html`<p>Something went wrong.</p>`],
  ["ready",   () => html`<data-table .rows=${this.rows}></data-table>`],
], () => html`<p>Idle</p>`)}`

An object lookup or a switch statement in a helper method does the same, so use whichever reads best to your team. All of these have identical performance profiles.

Hide with CSS or remove with the template?

Removing and re-adding DOM is not always the right choice. Think about what state the hidden thing holds.

Approach Use when Effect
Conditional in the template The content is cheap or has no state DOM is removed and recreated
?hidden=${flag} or a class The content has state (input text, scroll, a playing video) DOM stays, only display changes
cache() directive You switch among large templates Remembers the old DOM for reuse

A video player inside a collapsible panel should be hidden with hidden, not removed, or it restarts every time. A rarely used settings dialog is better removed. Also remember that a hidden element still exists, so heavy children keep costing memory and run their connectedCallback.

Accessibility note: elements removed from the template disappear from the accessibility tree too. If you hide content visually with CSS but keep it in the DOM, screen readers may still read it unless you use hidden or display: none.

Common mistakes

  • Using && with a value that can be 0 or false, which renders text.
  • Returning undefined from a helper and expecting a placeholder. It renders nothing, which may be intended, but write nothing to show your intent.
  • Rebuilding an expensive subtree on every toggle instead of using hidden or cache.
  • Calling requestUpdate() unconditionally in updated(), which loops forever.
  • Using visibility: hidden and forgetting that the element still takes space and may be focusable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the nothing value do in a child expression?

    nothing is a sentinel that makes Lit render no content. In an attribute position it removes the attribute.
  2. 2. Why does when() take functions for its cases?

    The functions are called lazily, so the unused branch is never computed.
  3. 3. A panel contains a playing video that must keep its state when toggled. What is best?

    Hiding keeps the element in the DOM, so state such as playback position is preserved.
  4. 4. Which pattern avoids rendering the text 0 for an empty list?

    An explicit comparison with a ternary returns nothing for the empty case, while && would pass 0 through.

Summary

  • Use ordinary JavaScript for conditions: ternaries, early returns and helper methods.
  • nothing renders no node, and removes an attribute when used in attribute position.
  • when and choose are readable lazy alternatives for two or many branches.
  • Remove DOM for cheap, stateless content; hide it with hidden or CSS when it has state.
  • Beware && with numbers, and never call requestUpdate() unconditionally in updated().

Next: Lists and Repeating Templates