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.
- 01Spot the repeated setupName the code every component writes by hand, and move it into one class that each component extends.
- 02Write the four helpersBuild sheets once per class, copy one template into each element, draw without
innerHTML, and read static metadata once. - 03Read 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:
<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>- 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:
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.
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
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:
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.
| What the file does by hand | How 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 own | 15 of 27. |
Makes a <template> from a string | 16 of 27. |
| Attaches a shadow root | 18 of 27. |
Lists observedAttributes | 15 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.
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:
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:
<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>The class turns its styles into a sheet the first time it's asked. All three badges adopt the same two sheets.
- 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.
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.
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:
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:
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 asrenderRoot: 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:
<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>- In the tea-badge.js tab, lines 16 to 19 make
templatea 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.
<template>. Each of the three badges gets its own copy, made with importNode().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:
<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>The badge finds a shadow root already there. It keeps the span, and adopts its sheets.
- 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:
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().ReactiveTeacalls it once per batch. Line 16 calls yourrender(). - Line 17: if
render()returnedhtml`...`, 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:
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'supdate()does that.
Click into the box and type Happy. Then switch to innerHTML, and type it again:
<p><tea-note></tea-note></p><script type="module"> import "./tea-note.js";</script>html.js copies the template once, then writes only the number. The box you type in stays, with your text and focus.
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).
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:
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
observedAttributesonce, incustomElements.define()(lesson 3.4). Ours callsfinalize(). 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)isTeaElement.?.()callsfinalize()only if the parent has one.ReactiveTeadoesn't, soTeaElementstarts fromstart: 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:
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:
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 addswrappedto watch. Line 5 adds a dashed gold outline.
<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>GiftBadge has no finalized of its own yet, so it builds one: TeaBadge's lists, plus its own attribute and style.
- 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.
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.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?
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:
| Base class | Where do the styles go? | Where does the shadow root come from? | How does it draw? | Where is the class's description kept? |
|---|---|---|---|---|
| TeaElement | static 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 LitElement | static 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' UI5Element | static 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 Catalyst | It 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.
ReactiveElementruns the update cycle.LitElementextends it, and itsupdate()callsrender()and hands the result to lit-html (lines 162 to 172). observedAttributescallsfinalize()(lines 659 to 669).finalize()returns early when the class already has its ownfinalized(lines 860 to 917). A subclass starts with a copy of its parent's properties (lines 828 to 847).- Each
cssresult makes its sheet once, the first time an element needs it (lines 71 to 91).adoptStyles()adds a<style>element instead in browsers withoutadoptedStyleSheets(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 metadataobject (line 1364).getMetadata()walks up the class chain, merges every class's metadata, and keeps the result on the class, checked withhasOwnProperty()(lines 1476 to 1491). observedAttributescomes from that metadata (lines 1224 to 1226), and so does the tag thatdefine()registers (lines 1438 to 1469). The metadata's attribute list leaves out properties markednoAttribute(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
@controlleron 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 joinsdata-actionattributes 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 withhasOwnProperty()(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:
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
thisfromcreateRenderRoot(), so it draws in its own light DOM. Lit's docs for the same method say to returnthisfor that (lines 1110 to 1118). - Lines 26 to 30 write the text, as the old one did.
Here are all three on kitAfter191:
<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>- 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:
| File | Lines before | Lines on TeaElement | Lines saved |
|---|---|---|---|
| tea-kit/tea-price.js | 44 | 33 | 11 |
| tea-kit/tea-badge.js | 60 | 49 | 11 |
| tea-kit/tea-card.js | 177 | 169 | 8 |
| All three | 281 | 251 | 30 |
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()orsuper.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.
TeaElementdraws afterconnectedCallback(). - "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
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><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>It prints Sheet objects: 3. Every root adopts the base sheet and TeaBadge's sheet. The gift badge adds its own sheet, made once for GiftBadge.
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><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>It prints the line once. finalize() reads TeaBadge's template once. GiftBadge has no own template, so it uses its parent's, already parsed.
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><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>Only the tea-steep.js tab changes. It observes minutes, has a strong element in its template, and render() writes Steep for 3 minutes. The button changes the attribute, so it says Steep for 4 minutes.
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><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>Only the tea-stock.js tab changes: its attributeChangedCallback() calls the base class's. Now a new count asks for an update, so Sell one shows 4 left.
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><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>It prints kind, wrapped, ribbon. finalize() for RibbonBadge starts from GiftBadge's list, which starts from TeaBadge's, and adds ribbon at the end.
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><p><tea-note></tea-note></p><script type="module"> import "./tea-note.js";</script>Only the tea-note.js tab changes: render() returns html... and sets no innerHTML. html.js writes only the count, so the box keeps Mint and its focus, and the count says 4 of 40 letters.
Check your understanding
Question 1 of 7A class with
static stylesmakes three badges. When does TeaElement turn the styles into a sheet?Choose an answer to see the explanation.
Question 2 of 7Two badges are on the page. What does this code print?
Read the code, then predictJavaScriptconst [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.
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.
Question 4 of 7Why does finalize() check
Object.hasOwn(this, "finalized")instead ofthis.finalized?Choose an answer to see the explanation.
Question 5 of 7How many lines does this code print?
Read the code, then predictJavaScriptclass 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.
Question 6 of 7Why shouldn't render() set innerHTML?
Choose an answer to see the explanation.
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:
- Using custom elements, MDN.
- Web Components At Work: Using a base class, Thomas Wilburn.
- Web Components At Work: Custom element base class, Thomas Wilburn.
- Custom Element best practices, web.dev.
- Using shadow DOM, MDN.
- Document: adoptedStyleSheets property, MDN.
- Styles, Lit.
- css-tag.ts, at Lit 3.3.3, Lit.
- Using templates and slots, MDN.
- Document: importNode() method, MDN.
- DOM Standard: attach a shadow root, WHATWG.
- reactive-element.ts, at Lit 3.3.3, Lit.
- lit-element.ts, at Lit 3.3.3, Lit.
- Handling properties in custom element upgrades, Nolan Lawson.
- UI5Element.ts, UI5 Web Components.
- UI5ElementMetadata.ts, UI5 Web Components.
- getConstructableStyle.ts, UI5 Web Components.
- updateShadowRoot.ts, UI5 Web Components.
- controller.ts, at Catalyst 1.8.1, GitHub.
- core.ts, at Catalyst 1.8.1, GitHub.
- register.ts, at Catalyst 1.8.1, GitHub.
- bind.ts, at Catalyst 1.8.1, GitHub.
- auto-shadow-root.ts, at Catalyst 1.8.1, GitHub.
- lit-utils.mjs (MozLitElement), Mozilla.
- browser-compat-data, MDN.
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.