completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

A component base class

Write a web component base class that builds each stylesheet once, copies one template, redraws without losing focus, and reads its metadata once.

By the end, you can
  • 01
    Spot the repeated setupName the code every component writes by hand, and move it into one class that each component extends.
  • 02
    Write the four helpersBuild sheets once per class, copy one template into each element, draw without innerHTML, and read static metadata once.
  • 03
    Read a library's base classFind the same four helpers in Lit, UI5 Web Components, Catalyst, and Firefox's own components.

What is a web component base class?

Meena is adding a new component to the Leaf and Kettle kit. She opens tea-badge.js to copy how it starts. Before she writes a line of her own, she has copied a stylesheet, a template, a shadow root, a constructor, and a callback.

Every component in the kit starts the same way. Ravi fixed a bug in one of them last week, and then fixed it again in three more. Can all that setup live in one place?

Yes. A component base class is a class that sits between HTMLElement and your components. It does the setup every component repeats: the shadow root, the shared styles, the template copy, and the drawing. Each component extends it and writes only what makes it different.

This lesson writes one, called TeaElement, in element.js. Here is a badge built on it. Press the button:

Two badges built on a base classPop out in the code editor (opens in a new tab)HTML
<p>  <tea-badge kind="green">Organic</tea-badge>  <tea-badge>New harvest</tea-badge></p><button id="oolong">Make New harvest an Oolong</button><script type="module">  import "./tea-badge.js";  const badge = document.querySelectorAll("tea-badge")[1];  document.querySelector("#oolong").addEventListener("click", () => badge.setAttribute("kind", "oolong"));</script>
ResultLoading…
  • Lines 2 and 3 are two badges. The first has a kind, and the second has none.
  • Line 7 loads the badge's file. Line 9 gives the second badge a kind when you press the button.

The first badge says Green in bold, on dark green. The second is gray. After the press, it says Oolong, on brown. Now look at the whole badge:

tea-badge.js: a badge that says only what it isJavaScript
import { TeaElement } from "./element.js";

const kinds = new Map([
  ["green", "Green"],
  ["oolong", "Oolong"],
]);

export class TeaBadge extends TeaElement {
  static observed = ["kind"];
  static styles = [`
    :host { display: inline-block; padding: 0 6px; border-radius: 8px; background: dimgray; color: white; }
    :host([kind="green"]) { background: darkgreen; }
    :host([kind="oolong"]) { background: sienna; }
    #kind { font-weight: bold; }
  `];
  static template = `<span id="kind"></span> <slot></slot>`;

  render() {
    this.renderRoot.getElementById("kind").textContent = kinds.get(this.getAttribute("kind")) ?? "";
  }
}

customElements.define("tea-badge", TeaBadge);
  • Line 8 makes the badge a TeaElement, from the element.js tab.
  • Line 9 names the attribute to watch. Lines 10 to 15 are its CSS. Line 16 is its markup.
  • Lines 18 to 20 are render(): how the badge draws. It writes the kind's name into the span.

There is no constructor, no attachShadow(), and no attributeChangedCallback(). The badge describes itself, and TeaElement does the rest.

Real-life analogyThe house blend

Leaf and Kettle sells a vanilla tea, a mint tea, and a ginger tea. Each one starts from the same house blend. Ravi mixes the blend once, then adds only the flavour. When he finds a better leaf for the blend, every tea gets better at once.

In real life: The house blend
In JavaScript: TeaElement, the base class
In real life: The vanilla or the mint
In JavaScript: A badge's own CSS, markup, and render()
In real life: Starting each new tea from the blend
In JavaScript: class TeaBadge extends TeaElement
In real life: Improving the blend once
In JavaScript: A fix in element.js that every component gets
The main idea

Write the setup once. A base class holds what every component repeats. Each component describes itself in a few static fields and a render() method. Then a fix in the base class reaches every component.

A base class uses JavaScript's extends and super, from the inheritance lesson. You met one already: lesson 17.4 wrote TeaFormControl for the kit's form controls. This one is for every component.

What code does every custom element repeat?

Here is the kit's badge before this lesson. This is its class, from lesson 18.5's kit:

The old badge's class, with its setup written by handJavaScript
export class TeaBadge extends HTMLElement {
  static observedAttributes = ["kind"];

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.adoptedStyleSheets = [base, sheet];
    this.shadowRoot.append(template.content.cloneNode(true));
  }

  attributeChangedCallback(name, oldValue, newValue) {
    this.shadowRoot.getElementById("kind").textContent = kinds.get(newValue) ?? "";
  }
}
  • Line 2 lists the attribute to watch.
  • Lines 4 to 9 are the constructor. Line 6 attaches a shadow root. Line 7 adopts the kit's base sheet, then the badge's. Line 8 copies the template into the root.
  • Lines 11 to 13 draw the kind when the attribute changes.

Above the class, the file makes its sheet and its template, once. Only lines 2 and 12 say anything about badges: the attribute, and what to draw. The rest is setup that any component could have.

MDN lists what a constructor may do: set up state, add listeners, and make a shadow root (MDN). It must not read attributes or children. For an element the parser makes, they aren't there yet. Lesson 3.2 showed getAttribute() returning null there. So drawing waits for connectedCallback().

Now count the kit. Read each row across: a piece of setup, then how many of the kit's components write it.

Setup the kit's components write by hand
What the file does by handHow many of the kit's components do it?
Makes a stylesheet with new CSSStyleSheet()15 of 27.
Adopts the kit's base sheet before its own15 of 27.
Makes a <template> from a string16 of 27.
Attaches a shadow root18 of 27.
Lists observedAttributes15 of 27.
Hands early properties to their setters (lesson 4.2)11 of 27.
Registers its tag with customElements.define()27 of 27.

That's one kit, written by one team. The web.dev checklist for custom elements asks for the same things in every element: a shadow root made in the constructor, a :host display, and properties set before the upgrade handled (web.dev). A base class can do each of those once.

Thomas Wilburn built web components at NPR. He says a good base class doesn't have to be long, and that this is mostly what libraries like LitElement do (his book). Ours stays small too.

Where TeaElement sits

Lesson 18.1's ReactiveTea already does one job: it joins many changes into one update(), in a microtask (lesson 18.1). TeaElement extends it and adds the rest: styles, the template, the shadow root, and render(). Lit is built in the same two layers, as you'll see near the end.

A family tree of classes. HTMLElement is at the top. TeaFormControl, for form controls, extends HTMLElement on the left. ReactiveTea, the update cycle, extends HTMLElement on the right. TeaElement, which adds styles, a template, and render, extends ReactiveTea. TeaBadge, TeaPrice, and TeaCard extend TeaElement.HTMLElementTeaFormControlform controlsReactiveTeaupdate cycleTeaElementstyles, template, renderTeaBadgeTeaPriceTeaCardeach adds only what is its own
Each arrow points from a class to the class it extends. ReactiveTea gives TeaElement its update cycle. TeaElement adds styles, a template, and render(). The kit's form controls keep their own base, TeaFormControl.

TeaFormControl stays where it is. It gives form controls what a native input has, and it doesn't draw. A control that wants both bases needs a way to mix them, which lesson 17.4 began and lesson 19.3 finishes.

How does a base class build each stylesheet once?

A constructed stylesheet is a CSSStyleSheet you make in JavaScript. Many shadow roots can adopt the same one (MDN). A change to it reaches every root that adopted it (MDN). Lesson 11.5 shared one sheet between three cards by hand.

In TeaElement, a component lists its CSS in static styles. Each entry goes through this function:

element.js: turning one entry of static styles into a sheetJavaScript
function toSheet(style) {
  if (style instanceof CSSStyleSheet) return style;
  const sheet = new CSSStyleSheet();
  sheet.replaceSync(style);
  return sheet;
}
  • Line 2 keeps a sheet that's already a CSSStyleSheet, as it is.
  • Lines 3 and 4 make a new sheet from CSS text, with replaceSync(). Line 5 returns it.

Who calls it, and how often? In the element.js tab, line 19 calls toSheet() on each style. That line is in finalize(), which runs once per class. Line 37 adopts the list in each new shadow root. Try it against a base class that makes the sheets in each constructor:

Playground: sheets made once, or for every badge
Three badges, and the sheets they adoptPop out in the code editor (opens in a new tab)HTML
<p>  <tea-badge kind="green">Organic</tea-badge>  <tea-badge>New harvest</tea-badge>  <tea-badge kind="oolong">Rare</tea-badge></p><script type="module">  import { base } from "./base.js";  import "./tea-badge.js";  const roots = [...document.querySelectorAll("tea-badge")].map((badge) => badge.shadowRoot);  const sheets = new Set(roots.flatMap((root) => root.adoptedStyleSheets));  console.log(`Sheet objects in 3 badges: ${sheets.size}`);  console.log(`Base sheet first in each: ${roots.every((root) => root.adoptedStyleSheets[0] === base)}`);</script>
ResultLoading…
Try it yourself
Sheets made once, in finalize()

The class turns its styles into a sheet the first time it's asked. All three badges adopt the same two sheets.

Only the element.js tab changes. Each choice prints how many different sheet objects the three badges hold.
  • Lines 2 to 4 are three badges. Line 9 collects their shadow roots.
  • Line 10 puts every adopted sheet in a Set, which keeps one of each object. Line 11 prints how many.
  • Line 12 checks that the kit's base sheet comes first in every root.

Made once per class, it prints Sheet objects in 3 badges: 2: the base sheet and the badge's sheet. Made in each constructor, it prints Sheet objects in 3 badges: 4. Both print Base sheet first in each: true.

Two windows, badge 1 and badge 2, each with an adoptedStyleSheets list of two slots, 0 and 1. In the middle are two sheets: base and badge sheet. Slot 0 of both lists points at base. Slot 1 of both lists points at badge sheet.badge 1[0][1]badge 2[0][1]basebadge sheetmade once, in finalize()
Each badge's shadow root has its own list, but both lists hold the same two sheets: the kit's base sheet and the badge's sheet. finalize() made them once, for the class.

The two shared sheets are the point. With a hundred badges, the class still holds two sheets. The browser parses the badge's CSS once.

Real-life analogyOne clock on the wall

The tea room has one clock on the wall. Every table looks at the same clock. When Asha sets it forward in spring, every table sees the new time. Nobody puts a clock on each table.

In real life: The clock on the wall
In JavaScript: One CSSStyleSheet for the class
In real life: Each table looking up at it
In JavaScript: Each shadow root adopting the sheet
In real life: Setting the clock once
In JavaScript: replaceSync() once, in finalize()
In real life: A clock on every table
In JavaScript: A new sheet in every constructor

An entry can be a sheet too. A CSS module script gives you one: import sheet from "./tea-badge.css" with { type: "css" }, from lesson 11.6. Chrome 123 and Firefox 147 support it, and Safari doesn't yet. So the kit keeps its CSS as text.

A subclass adds to its parent's sheets

Line 19 puts the parent class's sheets first, then the class's own. The kit's base sheet always comes first, as lesson 12.6 set up. Lit does it differently. A Lit subclass writes its parent's styles into its own list: [SuperElement.styles, css`...`] (Lit). Both work. Ours saves a line in every subclass.

How does a base class reuse one template?

A <template> holds markup the browser parses but doesn't show. You copy its content into the page with JavaScript (MDN). Lesson 7.1 made one template per file and cloned it in each constructor. TeaElement does that for every class:

element.js: making the template onceJavaScript
function toTemplate(markup) {
  const template = document.createElement("template");
  template.innerHTML = markup;
  return template;
}
  • Line 2 makes a <template>. Line 3 parses the markup into it. Line 4 returns it.
  • finalize() calls it once per class, on line 20 of element.js. A class without its own template uses its parent's.

Each element then gets its own copy, when it's made:

element.js: the constructor and createRenderRoot()JavaScript
  constructor() {
    super();
    this.renderRoot = this.createRenderRoot();
  }

  createRenderRoot() {
    const { sheets, template } = this.constructor.finalize();
    let root = this.shadowRoot;
    if (!root) {
      root = this.attachShadow({ mode: "open" });
      if (template) root.append(document.importNode(template.content, true));
    }
    root.adoptedStyleSheets = sheets;
    return root;
  }
  • Line 3 calls createRenderRoot() and keeps what it returns as renderRoot: where the component draws.
  • Line 7 gets the class's sheets and template from finalize().
  • Lines 9 to 12 run only when the element has no shadow root yet. Line 10 attaches one. Line 11 copies the template into it.
  • Line 13 adopts the sheets. Line 14 returns the root.

Line 11 copies with document.importNode(). It makes the copy in the page's document, so custom elements inside it upgrade as they're copied (MDN). Lesson 7.1 compared it with cloneNode().

The markup could live in its own file. A text module gives you a file's text as a string: import markup from "./tea-badge.html" with { type: "text" }. Chrome 155 and Firefox 153 support it, and Safari doesn't yet (browser-compat-data). So the kit keeps its markup in the class.

Now count the reads. This page's badge prints a line each time its template is read:

Three badges from one templatePop out in the code editor (opens in a new tab)HTML
<p>  <tea-badge kind="green">Organic</tea-badge>  <tea-badge>New harvest</tea-badge>  <tea-badge kind="oolong">Rare</tea-badge></p><script type="module">  import "./tea-badge.js";  const spans = [...document.querySelectorAll("tea-badge")].map((badge) => badge.shadowRoot.getElementById("kind"));  console.log(`Spans: ${spans.length}, all different: ${new Set(spans).size === spans.length}`);</script>
ResultLoading…
  • In the tea-badge.js tab, lines 16 to 19 make template a getter: a method that runs when you read the property. Line 17 prints.
  • On the page, line 8 finds the span inside each badge. Line 9 prints how many, and whether they're all different.

It prints TeaBadge's template was read once, for three badges. Then Spans: 3, all different: true. One template, three copies.

On the left, static template. An arrow marked parsed once leads to one template element. Three arrows lead from the template to three copies: badge 1's copy, badge 2's copy, and badge 3's copy.static templateparsed once<template>badge 1's copybadge 2's copybadge 3's copycopied once per badge
The badge's markup is parsed once, into one <template>. Each of the three badges gets its own copy, made with importNode().
Real-life analogyOne biscuit cutter

The tea room bakes shortbread. The baker shapes one metal cutter, then presses out every biscuit with it. Some days a tray arrives from the bakery, already baked. Nobody cuts those again. They go straight onto the plate.

In real life: Making the cutter
In JavaScript: toTemplate(), once per class
In real life: Pressing out a biscuit
In JavaScript: importNode() in each element
In real life: A biscuit that came baked from the bakery
In JavaScript: A shadow root the HTML already holds
In real life: Not cutting it again
In JavaScript: Keeping this.shadowRoot

A shadow root the HTML already holds

Back in createRenderRoot(), why does line 8 check this.shadowRoot first? HTML can hold a shadow root: <template shadowrootmode="open"> inside an element. This is declarative shadow DOM. The browser builds that root while it reads the HTML, before the class loads. So a server can send a component already drawn. Server rendering teaches it in full.

When the class finally loads, what happens to that root? Try both ways:

Playground: a shadow root that came in the HTML
A badge whose HTML holds its shadow root, before its class loadsPop out in the code editor (opens in a new tab)HTML
<tea-badge kind="green"><template shadowrootmode="open"><span id="kind">Green</span> <slot></slot></template>Organic</tea-badge><script type="module">  const badge = document.querySelector("tea-badge");  const sent = badge.shadowRoot.getElementById("kind");  await import("./tea-badge.js");  console.log(`Same span as the HTML sent: ${badge.shadowRoot.getElementById("kind") === sent}`);  console.log(`Spans in the shadow root: ${badge.shadowRoot.querySelectorAll("span").length}`);</script>
ResultLoading…
Try it yourself
createRenderRoot() keeps the root the HTML sent

The badge finds a shadow root already there. It keeps the span, and adopts its sheets.

Only the element.js tab changes. Each choice prints whether the span from the HTML is still there.
  • Line 1 is a badge with its shadow root written in HTML, already showing Green.
  • Line 4 keeps that span. Line 5 loads the class, so the badge upgrades.
  • Line 6 asks whether the span is the same one. Line 7 counts the spans.

Reusing the root prints Same span as the HTML sent: true and Spans in the shadow root: 1. Attaching every time prints false and 1.

Attaching didn't throw. The DOM Standard says what attachShadow() does to a declarative root of the same mode: it removes all its children and returns it (DOM Standard). So a class that always attaches throws away what the HTML sent, and builds it again. The kit's old badge did that too. A second call would throw.

Lit's createRenderRoot() makes the same check: this.shadowRoot ?? this.attachShadow(...) (lines 1119 to 1130). Why it matters: a page can send components already drawn, and the base class keeps them.

How do you re-render a web component without losing focus?

Change only what changed. Never replace the whole shadow root. Here is how TeaElement decides when to draw, and how:

element.js: the callbacks, update(), and render()JavaScript
  connectedCallback() {
    for (const name of this.constructor.finalize().observed) {
      if (!Object.hasOwn(this, name)) continue;
      const value = this[name];
      delete this[name];
      this[name] = value;
    }
    this.requestUpdate();
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue !== newValue && this.isConnected) this.requestUpdate();
  }

  update(changed) {
    const result = this.render(changed);
    if (result) renderInto(result, this.renderRoot);
  }

  render(changed) {}
  • Lines 1 to 9 are connectedCallback(). Lines 2 to 7 are the upgrade fix from lesson 4.2. A value set on the element before its class loaded goes to its setter. Line 8 asks for the first update.
  • Lines 11 to 13: an observed attribute changed. Line 12 asks for an update, if the value is new and the element is on the page.
  • Lines 15 to 18 are update(). ReactiveTea calls it once per batch. Line 16 calls your render().
  • Line 17: if render() returned html`...`, html.js writes it into the root.
  • Line 20 is the empty render() a subclass replaces.

Nolan Lawson calls the upgrade fix something you only need when you write your own custom elements, and that frameworks handle for you (his post). A base class is how you handle it once.

Line 17 is the render helper. Lesson 18.2 built html.js: it copies a template once, then writes only the values that changed. Here is a gift note box with a letter count:

tea-note.js: render() returns htmlJavaScript
import { html } from "./html.js";
import { TeaElement } from "./element.js";

export class TeaNote extends TeaElement {
  #text = "";

  constructor() {
    super();
    this.renderRoot.addEventListener("input", (event) => {
      this.#text = event.target.value;
      this.requestUpdate();
    });
  }

  render() {
    return html`<input aria-label="Gift note" maxlength="40"> ${this.#text.length} of 40 letters`;
  }
}

customElements.define("tea-note", TeaNote);
  • Line 5 is the text typed so far, in a private field. Lines 9 to 12 keep it up to date and ask for an update.
  • Line 16 returns the box and the count. It doesn't touch the page. TeaElement's update() does that.

Click into the box and type Happy. Then switch to innerHTML, and type it again:

Playground: render() with html, or with innerHTML
A gift note with a letter countPop out in the code editor (opens in a new tab)HTML
<p><tea-note></tea-note></p><script type="module">  import "./tea-note.js";</script>
ResultLoading…
Try it yourself
Only the count changes

html.js copies the template once, then writes only the number. The box you type in stays, with your text and focus.

Only line 16 of the tea-note.js tab changes. Click the box in the result and type Happy.

With html, the box keeps Happy, stays focused, and the count says 5 of 40 letters. With innerHTML, the box ends up with only H, and the count says 1 of 40 letters. Your cursor is gone.

The first letter asked for an update. innerHTML threw the box away and made a new one, with no focus. The other letters went nowhere. Lesson 7.3 showed the same loss. Wilburn hit it at NPR: rewriting a component's content means finding a way to keep its listeners and input state (his case study).

Real-life analogyWriting the total on the guest's form

A guest is filling in a long order form at the counter. Asha needs to update the total. She writes the new number at the bottom, and the guest keeps writing. She never takes the form away and hands over a blank one.

In real life: The guest's half-filled order form
In JavaScript: The box, with its text and focus
In real life: Writing the new total at the bottom
In JavaScript: html.js writing only the count
In real life: Handing over a fresh blank form
In JavaScript: Setting innerHTML
In real life: The guest starting again
In JavaScript: Lost text and focus

A component can also skip html.js. The badge's render() writes one span's text, and returns nothing. Both ways change only what changed. Why it matters: every component on the base class gets a safe way to draw, and nobody needs to remember the trap.

What is component metadata?

Metadata is a description of a class, kept on the class: what it watches, how it looks, what it holds. observed, styles, and template are the badge's. They're static fields: properties of the class itself, not of each element (the static members lesson). The base class reads them once:

element.js: observedAttributes and finalize()JavaScript
  static get observedAttributes() {
    return this.finalize().observed;
  }

  static finalize() {
    if (Object.hasOwn(this, "finalized")) return this.finalized;
    const parent = Object.getPrototypeOf(this).finalize?.() ?? start;
    const own = (name, none) => (Object.hasOwn(this, name) ? this[name] : none);
    const markup = own("template", "");
    this.finalized = {
      observed: [...parent.observed, ...own("observed", [])],
      sheets: [...parent.sheets, ...own("styles", []).map(toSheet)],
      template: markup ? toTemplate(markup) : parent.template,
    };
    return this.finalized;
  }
  • Lines 1 to 3: the browser reads observedAttributes once, in customElements.define() (lesson 3.4). Ours calls finalize(). So each class is finalized when it's defined.
  • Line 6 returns the description if this class already built its own.
  • Line 7 gets the parent class's description. Object.getPrototypeOf(TeaBadge) is TeaElement. ?.() calls finalize() only if the parent has one. ReactiveTea doesn't, so TeaElement starts from start: no attributes, the base sheet, and no template.
  • Line 8 reads a static field only if this class wrote it itself. Line 9 reads the markup.
  • Lines 10 to 14 build the description: the parent's lists, then this class's own.

Why Object.hasOwn()?

A subclass sees its parent's static fields. Run this:

A subclass reads its parent's static fieldPop out in the code editor (opens in a new tab)JavaScript
class TeaBadge {
  static observed = ["kind"];
}
class GiftBadge extends TeaBadge {}
console.log(GiftBadge.observed === TeaBadge.observed);
console.log(Object.hasOwn(GiftBadge, "observed"));

Line 4 gives GiftBadge no fields of its own. Line 5 prints true: it finds TeaBadge's list, the same array. Line 6 prints false: the list isn't its own. Object.hasOwn() asks whether the object itself has the property, not its parents (inherited statics).

So a check like if (this.finalized) would find the parent's description. Here is a gift badge that adds an attribute and a style:

gift-badge.js: a badge that adds to TeaBadgeJavaScript
import { TeaBadge } from "./tea-badge.js";

export class GiftBadge extends TeaBadge {
  static observed = ["wrapped"];
  static styles = [`:host([wrapped]) { outline: 2px dashed goldenrod; outline-offset: 2px; }`];
}

customElements.define("gift-badge", GiftBadge);
  • Line 3 extends TeaBadge. Line 4 adds wrapped to watch. Line 5 adds a dashed gold outline.
Playground: the description kept on each class, or inherited
A badge and a gift badgePop out in the code editor (opens in a new tab)HTML
<p>  <tea-badge kind="green">Organic</tea-badge>  <gift-badge kind="oolong" wrapped>Gift box</gift-badge></p><script type="module">  import { GiftBadge } from "./gift-badge.js";  const gift = document.querySelector("gift-badge");  console.log(`GiftBadge observes: ${GiftBadge.observedAttributes.join(", ")}`);  console.log(`Sheets in the gift badge: ${gift.shadowRoot.adoptedStyleSheets.length}`);</script>
ResultLoading…
Try it yourself
Each class keeps its own description

GiftBadge has no finalized of its own yet, so it builds one: TeaBadge's lists, plus its own attribute and style.

Only line 13 of the element.js tab changes: the check at the start of finalize().
  • Line 3 is a gift badge with a kind and wrapped.
  • Line 8 prints what it watches. Line 9 counts its sheets.

With Object.hasOwn(), it prints GiftBadge observes: kind, wrapped and Sheets in the gift badge: 3, and the outline shows. With this.finalized, it prints GiftBadge observes: kind and Sheets in the gift badge: 2, with no outline.

A table of three classes, each with what it observes and which sheets it adopts. TeaElement observes none and adopts base. TeaBadge observes kind and adopts base and badge. GiftBadge observes kind and wrapped and adopts base, badge, and gift. Arrows go down each column, from a parent's list to its subclass's list.classobservedsheetsTeaElementnonebaseTeaBadgekindbase, badgeGiftBadgekind, wrappedbase, badge, gift
finalize() runs once per class. Each class starts from its parent's lists and adds its own, so GiftBadge observes two attributes and adopts three sheets. Each result is kept on its own class.
Real-life analogyA card on every jar

Each tea jar at Leaf and Kettle has a card saying what's inside. When a new blend joins the menu, Ravi copies the base tea's card and adds a line. He tapes it to the new jar. If he only pointed at the base tea's jar, the new line would have nowhere to go.

In real life: The card on a jar
In JavaScript: The class's finalized description
In real life: Writing it when the tea joins the menu
In JavaScript: finalize(), run by define()
In real life: Copying the base tea's card, then adding a line
In JavaScript: The parent's lists, plus the class's own
In real life: Taping it to its own jar
In JavaScript: Object.hasOwn(this, "finalized")

Firefox's own components hit the same thing. Their base class gives each class its own array with Object.hasOwn(). Its comment says that changing an inherited one would leak attributes into every sibling class (lines 133 to 137).

Why not a static block?

A static block is code in a class body that runs once, when the class is made (static blocks). Could TeaElement finalize in one?

A static block runs for its own classPop out in the code editor (opens in a new tab)JavaScript
class TeaElement {
  static {
    console.log(`A static block ran for ${this.name}`);
  }
}
class TeaBadge extends TeaElement {}
class GiftBadge extends TeaBadge {}

Lines 2 to 4 are the block. It prints A static block ran for TeaElement, and nothing more. Lines 6 and 7 make two subclasses, and neither runs it. So a block in TeaElement can never describe TeaBadge. That's why finalize() runs on demand, for each class, and keeps the answer.

What do Lit, UI5, and Catalyst put in their base classes?

The same four helpers, in different shapes. Read each row across, one base class at a time:

Four base classes and their helpers
Base classWhere do the styles go?Where does the shadow root come from?How does it draw?Where is the class's description kept?
TeaElementstatic styles, made into sheets once per class, after the base sheet.createRenderRoot(): the root the HTML sent, or a new one with a copy of the template.render() writes the root, or returns html for html.js.finalize() keeps it on each class, checked with Object.hasOwn().
Lit's ReactiveElement and LitElementstatic styles, one sheet per css result, with a <style> fallback.createRenderRoot(): this.shadowRoot, or a new root, on the first connection.LitElement's update() calls render(), and lit-html writes it.finalize() keeps it on each class, checked with hasOwnProperty().
UI5 Web Components' UI5Elementstatic styles, one sheet per tag, after the shared component styles.The constructor: the root the HTML sent, marked to hydrate, or a new one.ctor.renderer, after the sheets are adopted.getMetadata() merges every class's static metadata, once per class.
GitHub's CatalystIt has no style helper.connectedCallback() copies a <template data-shadowroot> child.It has no renderer. It joins data-action attributes in your HTML to your methods.A decorator, @controller, wraps your class. There is no base class.

Lit

  • Lit splits its base in two, like ours. ReactiveElement runs the update cycle. LitElement extends it, and its update() calls render() and hands the result to lit-html (lines 162 to 172).
  • observedAttributes calls finalize() (lines 659 to 669). finalize() returns early when the class already has its own finalized (lines 860 to 917). A subclass starts with a copy of its parent's properties (lines 828 to 847).
  • Each css result makes its sheet once, the first time an element needs it (lines 71 to 91). adoptStyles() adds a <style> element instead in browsers without adoptedStyleSheets (lines 170 to 190).
  • Lit makes the render root on the first connection, not in the constructor (lines 1137 to 1143).

UI5 Web Components

  • Each class has a static metadata object (line 1364). getMetadata() walks up the class chain, merges every class's metadata, and keeps the result on the class, checked with hasOwnProperty() (lines 1476 to 1491).
  • observedAttributes comes from that metadata (lines 1224 to 1226), and so does the tag that define() registers (lines 1438 to 1469). The metadata's attribute list leaves out properties marked noAttribute (lines 151 to 153).
  • One sheet per tag, kept in a Map (lines 17 to 29). Each root adopts the shared component styles first, then the class's sheet (line 18), as ours adopts the base sheet first.
  • The constructor attaches a root only when there isn't one. A root from the HTML is marked to hydrate (lines 275 to 292).

GitHub's Catalyst

  • Catalyst has no base class. You put @controller on your own class (lines 9 to 20). It wraps your callbacks on the prototype (lines 15 to 33), and registers a tag made from the class name (line 12).
  • It copies a <template data-shadowroot> child into a new shadow root (lines 1 to 11). It joins data-action attributes in your HTML to your methods (lines 3 to 12). Its metadata copies the parent's when a class has none of its own, checked with hasOwnProperty() (lines 85 to 98).

Firefox

Firefox builds parts of its own design system, like its inputs, as web components (lines 262 to 284). Their base, MozLitElement, extends LitElement (line 122). It adds what a browser team needs: a static queries list that becomes getters for parts of the root (lines 156 to 172), and dispatchOnUpdateComplete() for tests (lines 249 to 252). A base class can grow a layer at a time.

Rebuilding the kit on TeaElement

The kit gets the base class in kitAfter191:

  • tea-kit/element.js (new helper): TeaElement. It's the file this lesson built, with comments.
  • tea-kit/tea-badge.js and tea-kit/tea-card.js: the same CSS, markup, and behavior, on TeaElement.
  • tea-kit/tea-price.js: the same properties and text, on TeaElement.
  • tea-kit/custom-elements.json: the new module, and the new parent class of the badge and the card.

The price has no shadow root. It writes its text into itself. So it changes where it draws:

tea-kit/tea-price.js on TeaElementJavaScript
import { TeaElement } from "./element.js";

export class TeaPrice extends TeaElement {
  static observed = ["amount", "currency"];

  get amount() {
    return this.getAttribute("amount");
  }

  set amount(value) {
    this.setAttribute("amount", value);
  }

  get currency() {
    return this.getAttribute("currency");
  }

  set currency(value) {
    this.setAttribute("currency", value);
  }

  createRenderRoot() {
    return this;
  }

  render() {
    const amount = this.getAttribute("amount");
    const currency = this.getAttribute("currency") ?? "";
    this.textContent = `Price: ${amount} ${currency}`.trim();
  }
}

customElements.define("tea-price", TeaPrice);
  • Line 4 watches two attributes. Lines 6 to 20 are its two properties, as before.
  • Lines 22 to 24 return this from createRenderRoot(), so it draws in its own light DOM. Lit's docs for the same method say to return this for that (lines 1110 to 1118).
  • Lines 26 to 30 write the text, as the old one did.

Here are all three on kitAfter191:

The kit's badge, price, and card on TeaElementPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><p>Today: <tea-badge kind="green">Organic</tea-badge> <tea-price amount="4" currency="EUR"></tea-price></p><tea-card name="Sencha" price="4"><p>Grassy and bright</p></tea-card><script type="module">  import "./tea-kit/index.js";  import { TeaElement } from "./tea-kit/element.js";  for (const tag of ["tea-badge", "tea-price", "tea-card"]) {    console.log(`${tag} extends TeaElement: ${customElements.get(tag).prototype instanceof TeaElement}`);  }</script>
ResultLoading…
  • Lines 2 and 3 are a badge, a price, and a card.
  • Lines 7 to 9 print whether each tag's class extends TeaElement.

It prints tea-badge extends TeaElement: true, then the same for tea-price and tea-card. They look as they did. One thing changed: they draw in a microtask now, so a test awaits updateComplete before it reads them.

How many lines did the base class save? Read each row across:

Lines in each kit file, before and on TeaElement
FileLines beforeLines on TeaElementLines saved
tea-kit/tea-price.js443311
tea-kit/tea-badge.js604911
tea-kit/tea-card.js1771698
All three28125130

The three files lost 30 lines. element.js is 111 lines with its comments, so for three files the base class is longer than what it saves. The card saved the least: most of its code is what makes it a card.

The lines aren't the point. A fix now goes in one file. The badge and the card keep a shadow root the HTML sent, which the old ones emptied. And the next component starts at the part that makes it different. Lesson 19.2 goes further: declared attributes that bring their own properties.

Common mix-ups

  • "A subclass gets its own copy of each static field." No. It reads its parent's through inheritance. Object.hasOwn() tells them apart.
  • "A static block runs for every subclass." No. It runs once, for the class it's written in.
  • "render() can set innerHTML, and the base class will cope." No. Each update throws away the old elements, with their focus and typed text.
  • "A subclass can replace a callback and the base still works." No. Call super.connectedCallback() or super.attributeChangedCallback(), or the base never hears. Exercise 4 has this bug.
  • "The constructor can draw from the attributes." No. An element the parser makes has no attributes yet there. TeaElement draws after connectedCallback().
  • "attachShadow() on a declarative root throws." No. The first call empties it and returns it. The second call throws.
  • "Write assert { type: "css" } to import a CSS file." No. That syntax was removed. It is with { type: "css" } now.
  • "A base class makes the kit shorter." No. The three files lost 30 lines, and the base is longer. It saves fixing the same thing in many places.

Practice exercises

Exercise 1 · Warm-upCount a gift badge's sheets

Three badges and one gift badge. Predict how many different sheet objects the page prints, then run it.

<p>  <tea-badge kind="green">Organic</tea-badge>  <tea-badge>New harvest</tea-badge>  <tea-badge kind="oolong">Rare</tea-badge>  <gift-badge kind="green" wrapped>Gift box</gift-badge></p><script type="module">  import "./gift-badge.js";  const roots = [...document.querySelectorAll("tea-badge, gift-badge")].map((badge) => badge.shadowRoot);  console.log(`Sheet objects: ${new Set(roots.flatMap((root) => root.adoptedStyleSheets)).size}`);</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCount the template reads

    The tea-badge.js tab prints TeaBadge's template was read each time its template is read. How many times does the page print it?

    <p>  <tea-badge kind="green">Organic</tea-badge>  <tea-badge>New harvest</tea-badge>  <tea-badge kind="oolong">Rare</tea-badge>  <gift-badge kind="green" wrapped>Gift box</gift-badge>  <gift-badge>Gift card</gift-badge></p><script type="module">  import "./gift-badge.js";</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeWrite a steeping time

      Fill in the tea-steep.js tab on TeaElement. It should show Steep for 3 minutes, and change when the button changes minutes. What does it show after one press?

      <p><tea-steep minutes="3"></tea-steep></p><button id="longer">One minute longer</button><script type="module">  import "./tea-steep.js";  const steep = document.querySelector("tea-steep");  document.querySelector("#longer").addEventListener("click", () => {    steep.setAttribute("minutes", Number(steep.getAttribute("minutes")) + 1);  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFix the stock that never changes

        Press Sell one. The page prints the change, but the stock still says 5 left. Fix the tea-stock.js tab. What does it show after one press then?

        <p>Sencha: <tea-stock count="5"></tea-stock></p><button id="sell">Sell one</button><script type="module">  import "./tea-stock.js";  const stock = document.querySelector("tea-stock");  document.querySelector("#sell").addEventListener("click", () => {    stock.setAttribute("count", Number(stock.getAttribute("count")) - 1);  });</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeWhat does a ribbon badge watch?

          Predict what the page prints for RibbonBadge.observedAttributes.

          <p><ribbon-badge kind="green" wrapped ribbon="red">Birthday box</ribbon-badge></p><script type="module">  import { RibbonBadge } from "./ribbon-badge.js";  console.log(RibbonBadge.observedAttributes.join(", "));</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeMake the note keep your typing

            The tea-note.js tab draws with innerHTML. Fix it, then type Mint. What does the count say?

            <p><tea-note></tea-note></p><script type="module">  import "./tea-note.js";</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The base class quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A class with static styles makes three badges. When does TeaElement turn the styles into a sheet?

                Choose an answer to see the explanation.

              2. Question 2 of 7Two badges are on the page. What does this code print?

                Read the code, then predictJavaScript
                const [first, second] = document.querySelectorAll("tea-badge");
                const a = first.shadowRoot.adoptedStyleSheets;
                const b = second.shadowRoot.adoptedStyleSheets;
                console.log(a === b, a[1] === b[1]);

                Choose an answer to see the explanation.

              3. Question 3 of 7A host already has a declarative open shadow root. Its class calls this.attachShadow({ mode: "open" }). What happens?

                Choose an answer to see the explanation.

              4. Question 4 of 7Why does finalize() check Object.hasOwn(this, "finalized") instead of this.finalized?

                Choose an answer to see the explanation.

              5. Question 5 of 7How many lines does this code print?

                Read the code, then predictJavaScript
                class TeaElement {
                  static {
                    console.log(`A static block ran for ${this.name}`);
                  }
                }
                class TeaBadge extends TeaElement {}
                class GiftBadge extends TeaBadge {}

                Choose an answer to see the explanation.

              6. Question 6 of 7Why shouldn't render() set innerHTML?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which of these has no base class at all?

                Choose an answer to see the explanation.

              Key takeaways

              • A base class sits between HTMLElement and your components, and does the setup they all repeat.
              • Make each sheet once per class. Every element adopts the same objects, after the base sheet.
              • Parse the template once per class, and copy it into each element with importNode().
              • Keep a shadow root the HTML already holds. attachShadow() would empty it.
              • Draw in render(), after connectedCallback(). Change only what changed, never with innerHTML.
              • Read static metadata once, in finalize(), and keep it on each class with Object.hasOwn().
              • A subclass starts from its parent's lists, and a static block runs only for its own class.
              • Lit, UI5, and Firefox have the same helpers in their base classes. Catalyst uses a decorator instead.

              Remember the one-liner.
              A base class describes the setup once, and each component describes only itself.

              Sources

              The facts on this page come from these docs, posts, specifications, and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: Declaring attributes. Declare an attribute once, and get its property, its conversion, and its reflection.

              CompleteFrontend Clear concepts. Working examples.