Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Templates and Directives

Built-in Lit Directives

A tour of Lit's built-in directives: classMap, styleMap, ifDefined, live, ref, createRef, keyed, cache, guard, until, unsafeHTML and more, with runnable examples and when to use each.

A directive is a function you call inside a template expression to change how Lit renders that one spot. Plain expressions say "put this value here". A directive says "put it here, but do it this special way": merge a class list, set a style object, bind to an element reference, reuse DOM, wait for a promise. Lit ships a set of directives for the common jobs, and you can write your own.

Directives are imported from their own modules, so a page only pays for the ones it uses:

JavaScript
import { classMap } from "lit/directives/class-map.js";

In the live examples on this page we import them from the single CDN bundle, which exports all of them from one file.

A map of the directive family

Style and attributes

classMap Toggle classes with an object
styleMap Set inline styles from an object
ifDefined Remove attribute when undefined
live Compare with the live DOM value

Used in attribute positions

1 / 3

Some directives (repeat, when, choose) were already covered in Lists and Repeating Templates and Conditional Rendering. The rest follow.

ifDefined

ifDefined(value) sets an attribute to value, or removes the attribute when the value is undefined (and, since Lit 3, also for null). It is shorthand for value ?? nothing.

JavaScript
html`<img src=${ifDefined(this.src)} alt=${this.alt}>`

live: for form controls

Lit normally compares a new binding value to the previous binding value, not to what is actually in the DOM. For <input .value=${text}>, if the user types and your state does not change, Lit thinks nothing changed and leaves the typed text. That is usually what you want. But when the DOM can change behind Lit's back and you want the template to win, live(value) compares against the real DOM value instead.

live: force the DOM to match state

Edit both inputs and press Re-render. The normal input keeps your typing, because the bound value ("fixed") did not change. The live input snaps back to "fixed", since Lit now checks the actual DOM value. Use live for fields that your code must keep exactly equal to state, for example inputs that you reformat as the user types.

ref and createRef

Sometimes you need the real element: to call focus(), measure it, or hand it to a library. The ref directive attaches to an element, and createRef() makes a container for it.

Focus an element with ref

this.inputRef.value is undefined during the very first render(), because the element does not exist yet; it is set right after the DOM is committed. That is why the code reads it in an event handler (long after render) and calls requestUpdate() once in firstUpdated() for the little label. For simple lookups inside a LitElement you can also use this.renderRoot.querySelector(...) or the @query decorator, which is covered in the tooling chapter. ref can also take a callback function, ref((el) => ...), which runs when the element is created and with undefined when it is removed.

keyed

keyed(key, template) throws away the DOM and builds it fresh whenever the key changes. Use it to restart animations or reset the state of a child.

JavaScript
html`${keyed(this.userId, html`<profile-card .userId=${this.userId}></profile-card>`)}`

When userId changes, the old profile-card is removed and a new one is created, so it starts from its defaults instead of keeping state from the previous user.

cache

When a template switches between two big branches (tabs, wizard steps), Lit normally destroys the DOM of the branch it leaves. cache() wraps the expression and keeps the old branch's DOM in memory, so switching back is instant and keeps any state.

JavaScript
html`${cache(this.tab === "a" ? html`<tab-a></tab-a>` : html`<tab-b></tab-b>`)}`

The trade-off is memory: cached DOM stays alive. Use it for a handful of branches, not hundreds.

guard

guard(dependencies, fn) calls fn and re-renders its result only when one of the dependencies changed (by !==). It skips work for a part of the template that is expensive to build.

JavaScript
html`${guard([this.items], () => this.items.map((i) => expensiveRow(i)))}`

Since Lit's updates are already cheap, reach for guard only after measuring a real problem. Wrong dependencies lead to stale UI.

until, asyncAppend, asyncReplace

until shows a placeholder while a promise settles, then the result:

until: placeholder and result

The promise is created once and stored (this.quote), not created inside render(); otherwise every render would start a new request. For real data fetching, many teams prefer the Task controller from @lit/task, which tracks pending, complete and error states explicitly (see Reactive Controllers in Lit).

asyncAppend(asyncIterable) appends each value an async iterator produces (for example, chunks from a stream) and asyncReplace shows only the latest one.

unsafeHTML and unsafeSVG

unsafeHTML(string) parses a string as HTML and inserts the nodes. The name is a warning: it skips Lit's escaping. If the string can contain user input, an attacker can inject <img onerror=...> and run script on your page (XSS).

JavaScript
html`<div>${unsafeHTML(this.trustedHtmlFromCms)}</div>`

Only use it with HTML you generated or have sanitized, for example with DOMPurify. Prefer building templates. There is also unsafeSVG and unsafeMathML, plus templateContent(templateElement) to render a <template> already in the page.

styleMap, classMap, and more

classMap and styleMap were introduced in Styling Lit Components. Two additional helpers:

  • map(iterable, fn), range(start, end), and join(items, separator) build lists from any iterable.
  • choose and when write conditionals (see Conditional Rendering).

Rules that apply to all directives

  • Most directives must be used in a particular kind of binding. classMap only works in the class attribute; ref only in an element position; repeat and until only in child expressions. Using the wrong place throws an error in development builds.
  • Directives are imported by path so unused ones are not bundled.
  • You can write your own by extending Directive from lit/directive.js (for example, a tooltip or intersection directive). That is an advanced topic.

Common mistakes

  • Creating the promise for until inside render(), starting a new request on every render.
  • Using unsafeHTML with unsanitized text.
  • Reading a ref value during the first render, when it is still undefined.
  • Combining classMap with other text in the class attribute.
  • Using guard with the wrong dependency list, which freezes part of the UI.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which directive makes the template's value win over what the user typed in the DOM?

    live compares the new value to the actual DOM property, not to Lit's last bound value.
  2. 2. When is ref's element available?

    The element is created while Lit commits the template, so read the ref in updated() or in later event handlers.
  3. 3. What does cache() do?

    cache() holds on to the rendered DOM of inactive branches instead of destroying it.
  4. 4. Why is unsafeHTML dangerous?

    Any HTML in the string is parsed and inserted, including event-handler attributes, so never pass user input.

Summary

  • Directives are functions used in template expressions to customize one binding; import only the ones you need.
  • classMap, styleMap, ifDefined and live handle attributes and properties.
  • ref/createRef give access to elements after render; keyed, cache and guard control DOM reuse.
  • until, asyncAppend and asyncReplace render asynchronous values; create the promise outside render().
  • unsafeHTML is for trusted or sanitized HTML only.

Next: Template Composition and Reuse