Declaring attributes
Declare web component attributes once, then generate getters, setters, and attribute converters, reflect them without loops, and write it all as decorators.
- 01Declare attributes onceDescribe each attribute in one
static attributesmap, and let the base class turn it into observed attributes and properties. - 02Convert and reflect safelyRead attribute text with HTML's rules and a fallback, write your own converter, and reflect without an endless loop.
- 03Use decorators for attributesWrite the same declarations as standard or legacy TypeScript decorators, and know why both need a build step.
How do you declare attributes in a web component?
Ravi is adding a cup to the Leaf and Kettle order screen. It needs a size, a roast, and an iced switch. He starts a getter, a setter, and a callback for the size. Then he stops.
Two more attributes means two more of each. Every one turns text into a number, a word, or true and false. Can he describe each attribute once, and get the rest?
Yes. Declare each attribute once, in a list on the class: its type, its default, and whether it reflects. A base class reads the list and makes the rest: the watched attribute, a property, the conversion from text, and the write back.
Here is a cup built that way. Press the button:
<tea-cup size="4" roast="dark">Hojicha</tea-cup><button id="bigger">Bigger and iced</button><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); console.log(`size: ${cup.size} (${typeof cup.size}), roast: ${cup.roast}`); document.querySelector("#bigger").addEventListener("click", () => { cup.size += 1; cup.iced = true; console.log(cup.outerHTML); });</script>- Line 1 is a cup with a size of 4 and a dark roast.
- Line 6 prints the size, its type, and the roast.
- Lines 8 and 9 make the cup one size bigger, and iced. Line 10 prints the cup's HTML.
It prints size: 4 (number), roast: dark. The attribute holds the text 4, but the property is the number 4. So cup.size += 1 gives 5, where text would give 41. After the press, it prints <tea-cup size="5" roast="dark" iced="">Hojicha</tea-cup>. The cup says size 5, dark roast, iced, with a dashed border.
Now the whole cup:
import { TeaElement } from "./element.js";
export class TeaCup extends TeaElement {
static attributes = {
size: { type: Number, reflect: true, fallback: 3 },
roast: { values: ["light", "dark"], fallback: "light" },
iced: { type: Boolean, reflect: true },
};
static styles = [`
:host { display: inline-block; padding: 0 8px; border: 2px solid seagreen; border-radius: 8px; }
:host([iced]) { border-style: dashed; }
`];
static template = `<slot></slot>: <span id="order"></span>`;
render() {
const iced = this.iced ? ", iced" : "";
this.renderRoot.getElementById("order").textContent = `size ${this.size}, ${this.roast} roast${iced}`;
}
}
customElements.define("tea-cup", TeaCup);- Lines 4 to 8 are the declarations. Line 5:
sizeis a number, it reflects, and it's 3 when missing. - Line 6:
roastis light or dark, light by default. Line 7:icedis on or off, and reflects. - Lines 15 to 18 draw the cup from
this.size,this.roast, andthis.iced.
There's no getter, no setter, and no attributeChangedCallback(). Three lines describe three attributes.
size: { type: Number, reflect: true, fallback: 3 }, gives the cup four things: a watched attribute, a property, a way to read its text, and a way to write it back.The tea room's order form has a box for each choice. The size box takes a number. The roast has two circles, light and dark. Iced is a tick box. Every waiter fills in the same form. When a box is empty or messy, the kitchen makes the house choice.
- In real life: The printed order form
- In JavaScript: static attributes on the class
- In real life: A box that takes a number
- In JavaScript: type: Number
- In real life: Two circles, light and dark
- In JavaScript: values: ["light", "dark"]
- In real life: A tick box
- In JavaScript: type: Boolean
- In real life: The house choice for an empty or messy box
- In JavaScript: fallback
Declare each attribute once. Give it a type, a default, and say whether it reflects. The base class reads the declarations once, and makes the watched attribute, the property, the conversion, and the reflection.
Lesson 5.1 wrote these parts by hand. Lesson 5.2 gave the rules for reading text. This lesson writes them once, in TeaElement, the base class from lesson 19.1.
What goes in an attribute declaration?
A declaration is an object of options. Each option answers one question about the attribute. Read each row across:
| Option | What it does | In the cup |
|---|---|---|
type | How the text is read: String (the default), Number, or Boolean. | size is a Number, and iced is a Boolean. |
values | The only words allowed, in any case. Anything else gives the fallback. | roast takes light or dark. |
fallback | The value when the attribute is missing, or its text makes no sense. | size falls back to 3, and roast to light. |
reflect | Write the property back to the attribute when code sets it. | size and iced reflect. roast doesn't. |
attribute | A different attribute name. Without it, giftWrapped watches gift-wrapped. | The cup's names need no change. |
converter | Your own fromAttribute() and toAttribute(), in place of the rules above. | The cup doesn't need one. A steeping time does. |
Lit's static properties uses type, reflect, attribute, and converter the same way (Lit). values and fallback are the kit's own. They copy what built-in elements do with bad text.
TeaElement reads the map in finalize(), which runs once per class. Here it is, with its new lines:
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", "");
const attributes = new Map(parent.attributes);
for (const [name, options] of Object.entries({ ...own("attributes", {}), ...decorated(this) })) {
const declaration = { name, attribute: dashed(name), ...options, ...converterFor(options) };
attributes.set(declaration.attribute, declaration);
this.createProperty(declaration);
}
this.finalized = {
observed: [...new Set([...parent.observed, ...own("observed", []), ...attributes.keys()])],
attributes,
sheets: [...parent.sheets, ...own("styles", []).map(toSheet)],
template: markup ? toTemplate(markup) : parent.template,
};
return this.finalized;
}- Lines 1 to 3:
define()readsobservedAttributesonce, which finalizes the class. - Line 10 starts from the parent class's attributes, so a subclass adds to them.
- Line 11 goes through the class's own
static attributes, and any its decorators declared. - Line 12 makes a full declaration: the property's name, the attribute's name, the options, and two converter functions.
- Line 13 files it under the attribute's name, for the callback. Line 14 makes the property.
- Line 17 adds every declared attribute to the observed list, once each.
Why build the list here? The browser reads observedAttributes once, in define() (lesson 3.4). And attributeChangedCallback() runs only for names in that list (MDN). So the declarations must be ready by then. Static fields are.
Line 12 also calls dashed(), near the end of element.js. It turns a camelCase name into a dashed one, as the platform does: ariaChecked reflects aria-checked (MDN). Try a subclass:
<tea-cup size="4">Hojicha</tea-cup><gift-cup gift-wrapped>Sencha</gift-cup><script type="module"> import { TeaCup } from "./tea-cup.js"; class GiftCup extends TeaCup { static attributes = { giftWrapped: { type: Boolean, reflect: true } }; } customElements.define("gift-cup", GiftCup); console.log(`TeaCup watches: ${TeaCup.observedAttributes.join(", ")}`); console.log(`GiftCup watches: ${GiftCup.observedAttributes.join(", ")}`); console.log(`giftWrapped: ${document.querySelector("gift-cup").giftWrapped}`);</script>- Line 2 is a gift cup with
gift-wrapped. - Lines 5 to 7:
GiftCupextendsTeaCupand declares one more attribute. - Lines 9 to 11 print what each class watches, and the gift cup's new property.
It prints TeaCup watches: size, roast, iced, then GiftCup watches: size, roast, iced, gift-wrapped, then giftWrapped: true. The subclass kept its parent's three and added one. Why it matters: a component can grow a parent's attributes without copying them.
How does a base class generate getters and setters?
It writes them once, on the class's prototype: the object every element of the class shares. When code reads cup.size, JavaScript looks on the cup first, then on its prototype (the prototype chain). Line 14 of finalize() calls this:
static createProperty({ name, attribute, reflect, fromAttribute, toAttribute }) {
Object.defineProperty(this.prototype, name, {
get() {
return this.#values.has(name) ? this.#values.get(name) : fromAttribute(null);
},
set(value) {
const oldValue = this[name];
const text = toAttribute(value);
this.#values.set(name, fromAttribute(text));
if (reflect && this.#reflecting !== name) {
this.#reflecting = name;
if (text === null) this.removeAttribute(attribute);
else this.setAttribute(attribute, text);
this.#reflecting = null;
}
if (this.isConnected) this.requestUpdate(name, oldValue);
},
configurable: true,
enumerable: true,
});
}- Line 2 calls
Object.defineProperty(). It adds a property with a getter and a setter to an object, here the prototype (MDN, and property descriptors). - Line 4 is the getter. It gives the stored value. With none stored, it asks the converter about a missing attribute, which gives the fallback.
- Lines 7 to 9 start the setter. Line 8 turns the new value into attribute text. Line 9 reads that text back, and stores the result. The converters section shows why.
- Lines 10 to 15 write the attribute, for a declaration that reflects. The reflection section explains line 10.
- Line 16 asks for an update, as lesson 18.1's setters did.
Where do the values live? In #values, a private Map on each element, on line 11 of element.js. A private field starts with #, and only code inside the class can use it. So all cups share one getter and setter, and each keeps its own size. Check it:
<tea-cup size="4">Hojicha</tea-cup><tea-cup>Sencha</tea-cup><script type="module"> import { TeaCup } from "./tea-cup.js"; const [first, second] = document.querySelectorAll("tea-cup"); const size = Object.getOwnPropertyDescriptor(TeaCup.prototype, "size"); console.log(`On the prototype: get is a ${typeof size.get}, set is a ${typeof size.set}`); console.log(`On the first cup itself: ${Object.hasOwn(first, "size")}`); console.log(`Sizes: ${first.size} and ${second.size}`);</script>- Line 6 asks the prototype for its
sizeproperty. Line 7 prints what kind its getter and setter are. - Line 8 asks whether the first cup has a size of its own. Line 9 prints both sizes.
It prints On the prototype: get is a function, set is a function, then On the first cup itself: false, then Sizes: 4 and 3. The second cup has no attribute, so its getter gave the fallback.
TeaCup.prototype. Each keeps only its value. A class field gives cup 3 its own size, so JavaScript never reaches the prototype's.Leaf and Kettle has one price board on the wall. Every table reads it, so Ravi changes a price in one place. One day a waiter sticks a note on table 4: "Tea: 2". The guests there read the note and never look up. When Ravi changes the board, table 4 doesn't notice.
- In real life: The price board on the wall
- In JavaScript: The getter and setter on TeaCup.prototype
- In real life: Each table's own order
- In JavaScript: Each cup's value in #values
- In real life: A note stuck on table 4
- In JavaScript: A class field: the cup's own property
- In real life: Guests reading the note, not the board
- In JavaScript: JavaScript finding the own property first
Why does a class field break a generated property?
Ravi wants a size of 2 by default. He writes size = 2; in the class. That's a class field: a property each new element gets. Lesson 4.2 showed a field hiding a hand-written setter. Try it against a generated one:
<tea-cup size="4">Hojicha</tea-cup><tea-cup>Sencha</tea-cup><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); console.log(`size is the cup's own property: ${Object.hasOwn(cup, "size")}`);</script>Each cup gets its own size property after super() returns. It sits in front of the prototype's getter and setter, so TeaElement stops with an error.
- Lines 1 and 2 are two cups, one with a size and one without.
- Line 6 prints whether the first cup has a size of its own.
With the class field, it prints size is the cup's own property: true, and the same error twice: Error: tea-cup: the class field size hides its generated property. Both cups are blank. With fallback: 2, it prints false. The cups say size 4, light roast and size 2, light roast.
JavaScript adds a class field to each new element right after super() returns. It's the cup's own property, so JavaScript finds it before the prototype's getter and setter. Lit's docs describe the same trap (Lit). How does TeaElement catch it? In connectedCallback():
connectedCallback() {
for (const { name } of this.constructor.finalize().attributes.values()) {
if (Object.hasOwn(this, name)) {
throw new Error(`${this.localName}: the class field ${name} hides its generated property`);
}
}
for (const [name, value] of this.#early) this[name] = value;
this.#early.clear();
this.requestUpdate();
}- Lines 2 to 6 throw when a declared name is the element's own property.
- Line 7 hands values a page set before the class loaded to their setters, as lesson 4.2's pattern did. Line 8 forgets them.
Those early values were taken first, by the constructor, on lines 63 to 67 of element.js. It deletes them in TeaElement, before any subclass field exists (Nolan Lawson explains early values). So when a cup connects, an own property can only be a class field. Lit's development build throws the same kind of error, at its first update (lines 1452 to 1471).
TypeScript adds a twist. A field and an assignment look alike, but they do different things:
class Cup {
set size(value) {
console.log(`The setter got ${value}`);
}
}
class FieldCup extends Cup {
size = 2;
}
class AssignedCup extends Cup {
constructor() {
super();
this.size = 2;
}
}
new FieldCup();
new AssignedCup();It prints The setter got 2 once, for AssignedCup. Line 7's field makes a new property. Line 12's assignment calls the setter (assignment and definition). TypeScript writes your field either way, by its useDefineForClassFields setting (TypeScript). Read each row across:
| useDefineForClassFields | What TypeScript writes |
|---|---|
true, the default for an ES2022 target | size = 2;, a class field. It hides the setter. |
false | this.size = 2; in the constructor. It calls the setter. |
Lit asks TypeScript users of its legacy decorators for false (Lit). In TeaElement, the setter would then run in the constructor, and a reflecting setter would add an attribute. Lesson 3.2 showed what document.createElement() does then: it reports a NotSupportedError. So the kit takes every default from fallback.
How do attribute converters work?
An attribute is always text. A converter is a pair of functions that turn it into a value, and back. fromAttribute() reads text, and toAttribute() writes it. TeaElement builds the pair for each declaration in converters.js:
import { toFloat, toKeyword } from "./attribute-types.js";
const toText = (value) => (value === null || value === undefined ? null : String(value));
export function converterFor({ type = String, values, fallback = null, converter }) {
if (converter) return converter;
if (type === Boolean) return { fromAttribute: (text) => text !== null, toAttribute: (value) => (value ? "" : null) };
if (values) return { fromAttribute: (text) => toKeyword(text, values, fallback), toAttribute: toText };
if (type === Number) return { fromAttribute: (text) => toFloat(text, fallback), toAttribute: toText };
return { fromAttribute: (text) => text ?? fallback, toAttribute: toText };
}- Line 3 turns any value into text.
nullandundefinedgivenull, which means no attribute. - Line 6: a declaration with its own converter keeps it.
- Line 7: a Boolean is true whenever the attribute is there. Writing true gives empty text, and false removes it.
- Line 8: a keyword uses
toKeyword(). It matches in any case, and gives the fallback for other words. - Line 9: a number uses
toFloat(), HTML's rules for decimals, with the fallback. - Line 10: text stays text, or gives the fallback when it's missing.
Lines 8 and 9 reuse the kit's attribute-types.js, from lesson 5.2. It follows the HTML Standard, like built-in elements do.
fromAttribute() reads text with HTML's rules, and gives the fallback when it can't. toAttribute() writes a value back as text.A visitor orders in French. Asha puts it into English for the kitchen, and puts the kitchen's answer back into French. When she can't make out a word, she orders the house tea, as the menu says to.
- In real life: Asha, the translator
- In JavaScript: A converter
- In real life: French into English, for the kitchen
- In JavaScript: fromAttribute(): text into a value
- In real life: English back into French
- In JavaScript: toAttribute(): a value back into text
- In real life: A word she can't make out
- In JavaScript: Bad text, which gives the fallback
Type any text. The page writes it into all three attributes, and shows what each property makes of it:
<label>Text for all three attributes <input id="text" value="4 cups"></label><button id="remove">Remove them</button><p><tea-cup>Sencha</tea-cup></p><output></output><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); const text = document.querySelector("#text"); const names = ["size", "roast", "iced"]; const show = () => { document.querySelector("output").textContent = `size ${cup.size}, roast ${cup.roast}, iced ${cup.iced}`; }; text.addEventListener("input", () => { for (const name of names) cup.setAttribute(name, text.value); show(); }); document.querySelector("#remove").addEventListener("click", () => { for (const name of names) cup.removeAttribute(name); show(); }); for (const name of names) cup.setAttribute(name, text.value); show();</script>- Line 9 names the three attributes. Lines 13 to 16 write the box's text into each one, as you type.
- Lines 17 to 20: Remove them takes all three away.
It starts with 4 cups and shows size 4, roast light, iced true. The number rules read the 4 and stop at the space. Type DARK: size 3, roast dark, iced true. Type false: size 3, roast light, iced true. An iced attribute that's there is on, even with the text false. Press Remove them: size 3, roast light, iced false.
Why does the setter send a value through text, on lines 8 and 9 of createProperty()? So a property follows the attribute's rules. cup.roast = "burnt" stores light, like roast="burnt" does. Built-in elements behave the same: input.type = "burnt" gives back text (Jake Archibald). Lit doesn't. Its docs say a property keeps whatever value you assign (Lit).
A converter of your own
Some values need their own rules. A steeping time reads best as minutes and seconds, like 2:30. Press the button:
<tea-brew steep="2:30">Sencha</tea-brew><button id="longer">30 seconds longer</button><script type="module"> import "./tea-brew.js"; const brew = document.querySelector("tea-brew"); console.log(`steep: ${brew.steep} seconds`); document.querySelector("#longer").addEventListener("click", () => { brew.steep += 30; console.log(`steep="${brew.getAttribute("steep")}"`); });</script>It prints steep: 150 seconds. Press 30 seconds longer, and it prints steep="3:00". The brew says Sencha: steep for 180 seconds. Here is the converter, in the tea-brew.js tab:
import { TeaElement } from "./element.js";
const minutesAndSeconds = {
fromAttribute(text) {
const match = /^(\d+):([0-5]\d)$/.exec(text ?? "");
return match ? Number(match[1]) * 60 + Number(match[2]) : 180;
},
toAttribute(seconds) {
const whole = Math.round(seconds);
return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
},
};
export class TeaBrew extends TeaElement {
static attributes = {
steep: { converter: minutesAndSeconds, reflect: true },
};
static template = `<slot></slot>: steep for <span id="seconds"></span> seconds`;
render() {
this.renderRoot.getElementById("seconds").textContent = this.steep;
}
}
customElements.define("tea-brew", TeaBrew);- Lines 3 to 12 are the converter: an object with the two functions.
- Line 5 matches minutes, a colon, and two digits of seconds. Line 6 gives the total seconds, or 180 when the text doesn't match.
- Lines 9 and 10 write seconds back as minutes and seconds, with a leading zero.
- Line 16 declares
steepwith that converter. It reflects.
A date works the same way. Lit's tutorial on custom converters builds one for dates (Lit tutorial). Why it matters: any value that has a text form can be an attribute, with rules you choose.
How do you reflect a property without an endless loop?
Reflecting means writing a property back to its attribute (lesson 5.1). The setter does it on lines 10 to 15. But writing an attribute runs the callback, and the callback sets the property. Lesson 3.4 showed such a pair calling each other forever. First, when exactly does the callback run?
<tea-cup></tea-cup><script type="module"> class TeaCup extends HTMLElement { static observedAttributes = ["size"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`2. attributeChangedCallback: ${name} is now ${newValue}`); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); new MutationObserver(() => console.log("4. MutationObserver")).observe(cup, { attributes: true }); console.log("1. setAttribute starts"); cup.setAttribute("size", "5"); console.log("3. setAttribute returned");</script>- Lines 3 to 8 are a plain cup class whose callback prints.
- Line 11 starts a
MutationObserver, which also hears about attribute changes. - Lines 12 to 14 print, set the attribute, and print again.
It prints 1. setAttribute starts, 2. attributeChangedCallback: size is now 5, 3. setAttribute returned, and 4. MutationObserver. The callback ran inside setAttribute(), before it returned. The observer heard later, in a microtask.
The HTML Standard says why. setAttribute() is marked [CEReactions]. The browser runs its steps, then the custom element callbacks they queued, and only then returns (HTML Standard).
setAttribute(), while the mark is still set. So it knows the change is the setter's own, and doesn't copy it back.So the setter can leave a mark for its own callback. Back on lines 10 to 14 of createProperty(), line 11 sets #reflecting to the property's name. Line 13 writes the attribute. Line 14 clears the mark. The callback checks it:
attributeChangedCallback(attribute, oldValue, newValue) {
const declaration = this.constructor.finalize().attributes.get(attribute);
if (!declaration) {
if (oldValue !== newValue && this.isConnected) this.requestUpdate();
} else if (this.#reflecting !== declaration.name) {
this.#reflecting = declaration.name;
this[declaration.name] = declaration.fromAttribute(newValue);
this.#reflecting = null;
}
}- Line 2 finds the declaration for this attribute.
- Line 4: an attribute that's only observed, like the badge's
kind, asks for an update. - Line 5: a declared attribute, unless its own property is writing it right now.
- Lines 6 to 8 set the property from the new text, with the mark on. So the setter's line 10 doesn't write the attribute back.
Ravi keeps today's teas on a whiteboard and in the till. When the board changes, he copies it into the till. When the till changes, he writes it on the board. There's one marker. A change he sees while holding it is his own, so he doesn't copy it back.
- In real life: The whiteboard
- In JavaScript: The attribute
- In real life: The till
- In JavaScript: The property
- In real life: Holding the one marker
- In JavaScript: #reflecting set to the property's name
- In real life: Not copying his own change back
- In JavaScript: The callback skipping its own write
Now take the mark away. Press Set size to 5 with each choice:
<tea-cup>Hojicha</tea-cup><button id="five">Set size to 5</button><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); document.querySelector("#five").addEventListener("click", () => { cup.size = 5; console.log(`size ${cup.size}, attribute ${cup.getAttribute("size")}`); });</script>The setter marks size as reflecting, then writes the attribute. The callback runs inside setAttribute(), sees the mark, and skips the property.
With the guard, it prints size 5, attribute 5. Without it, the page reports RangeError: Maximum call stack size exceeded. The setter and the callback called each other until the call stack was full. Then the page carries on, and prints the same line. The browser reports an error thrown in a callback, instead of passing it to setAttribute()'s caller (HTML Standard). That's why this bug is easy to miss.
One mark covers both directions. Lit does the same with __reflectingProperty (lines 1183 to 1230 and 1233 to 1259). Its comment says the trick works because the callback is synchronous (lines 1213 to 1219).
What should a component do with a bad attribute value?
Use the default, and leave the attribute alone, as built-in elements do. Lesson 5.2 gave the rules. Here they are, next to the cup:
<input type="burnt"><button disabled="false">Order</button><tea-cup size="big" roast="burnt" iced="false">Sencha</tea-cup><script type="module"> import "./tea-cup.js"; const input = document.querySelector("input"); const button = document.querySelector("button"); const cup = document.querySelector("tea-cup"); console.log(`input.type: ${input.type}, button.disabled: ${button.disabled}`); console.log(`size: ${cup.size}, roast: ${cup.roast}, iced: ${cup.iced}`); const text = ["size", "roast", "iced"].map((name) => cup.getAttribute(name)); console.log(`The attributes still say: ${text.join(", ")}`);</script>- Line 1 is an input whose type is burnt. Line 2 is a button with
disabled="false". - Line 3 is a cup with a bad size, a bad roast, and
iced="false". - Lines 9 to 12 print the properties, then the attributes' text.
It prints input.type: text, button.disabled: true. Then size: 3, roast: light, iced: true: the cup falls back the same way. Then The attributes still say: big, burnt, false. Nothing rewrote the page's HTML.
Burton Smith asks for attributes that work "when set, unset, and poorly set" (his post). Here are the cup's three. Read each row across:
| Attribute | Set well | Not set | Set badly |
|---|---|---|---|
size | size="5" gives 5. | No attribute gives 3. | size="big" gives 3. |
roast | roast="DARK" gives dark. | No attribute gives light. | roast="burnt" gives light. |
iced | iced="" gives true. | No attribute gives false. | iced="false" gives true. |
One more rule: a default never becomes an attribute. On the converters page, Remove them left no attributes, and the size was still 3. Lit 3.3 added a useDefault option for this (changelog). It keeps a default from reflecting, and brings it back when the attribute goes (Lit).
Which attributes should reflect?
Every reflected change writes the HTML and runs the callback. Lesson 5.1 counted the cost. Cory LaViska's rules decide each reflect (his post):
- Reflect settings the page writes and styles, like
size, sotea-cup[size="5"]works. - Reflect states a person changes and others watch, like
iced,open, ordisabled. - Don't reflect objects, lists, or long text.
- Internal state, like brewing, isn't an attribute at all. Show it with a custom state and
:state(), as lesson 12.3 did. Don't declare it.
Lit's docs agree: attributes are input from the element's owner, so reflect sparingly (Lit). And when a rule is missing, the declarations grow without touching element.js: a subclass adds attributes, and a converter adds rules. Exercises 5 and 6 do both.
How do decorators declare attributes?
A decorator is a function you write after an @, in front of a class member. It runs once, when the class is made, and gets that member (decorators). Lit's @property() is one. TeaElement gets its own, attribute():
export function attribute(options = {}) {
return (target, context) => {
if (typeof context === "object") {
if (!Object.hasOwn(context.metadata, "attributes")) context.metadata.attributes = {};
context.metadata.attributes[context.name] = options;
} else {
const Class = target.constructor;
if (!Object.hasOwn(Class, "attributes")) Class.attributes = {};
Class.attributes[context] = options;
}
};
}
function decorated(Class) {
const metadata = Object.hasOwn(Class, Symbol.metadata) ? Class[Symbol.metadata] : {};
return Object.hasOwn(metadata, "attributes") ? metadata.attributes : {};
}- Line 1 takes the same options as static attributes. Line 2 returns the decorator.
- Line 3 tells the two kinds apart. A standard decorator gets a context object, with the member's name and the class's metadata.
- Lines 4 and 5 keep the options in the metadata.
decorated(), lines 14 to 17, reads them back forfinalize(). - Lines 7 to 9: a legacy TypeScript decorator gets the prototype and the name (legacy decorators). It adds the options to the class's own static attributes.
Lit's property() tells them apart the same way (lines 205 to 233). Line 6 of element.js adds Symbol.metadata when it's missing, because TypeScript only keeps metadata when it exists. Lit does that too (lines 432 to 434). Here is the cup with standard decorators:
import { TeaElement, attribute } from "./element.js";
export class TeaCup extends TeaElement {
@attribute({ type: Number, reflect: true, fallback: 3 })
accessor size: number;
@attribute({ values: ["light", "dark"], fallback: "light" })
accessor roast: string;
static template = `<slot></slot>: <span id="order"></span>`;
render() {
this.renderRoot.getElementById("order").textContent = `size ${this.size}, ${this.roast} roast`;
}
}
customElements.define("tea-cup", TeaCup);- Lines 4 and 5 declare
size: the decorator, thenaccessor size. - Lines 7 and 8 declare
roastthe same way.
accessor makes an auto-accessor: a getter and a setter on the prototype, with a private value behind them (auto-accessors). A standard decorator can't turn a field into a getter and setter, so it needs one already there (Lit 3 upgrade guide). finalize() then puts TeaElement's own in its place. The legacy version is the same, without the word accessor.
At the post office, a clerk stamps FRAGILE on a parcel. The stamp doesn't change what's inside. It tells the sorting room, later, how to handle it.
- In real life: The FRAGILE stamp
- In JavaScript: @attribute({ type: Number })
- In real life: The parcel it's on
- In JavaScript: accessor size
- In real life: The sorting room reading the stamps
- In JavaScript: finalize() reading the metadata
- In real life: Careful handling
- In JavaScript: The generated property
Do decorators work in the browser without a build step?
No. Decorators are still a proposal: TC39, the group that designs JavaScript, lists them at stage 2.7 (TC39). No browser runs them yet. Can I use marks every version of Chrome, Edge, Firefox, and Safari as not supported (Can I use). Chrome refuses the syntax:
class TeaCup extends HTMLElement {
@attribute({ type: Number })
accessor size;
}It throws a SyntaxError before it runs. So TypeScript or Babel turns decorators into plain JavaScript first. The playground runs what TypeScript made from tea-cup.ts, with three settings:
<p><tea-cup size="4" roast="dark">Hojicha</tea-cup></p><script type="module"> import { TeaCup } from "./tea-cup.js"; const cup = document.querySelector("tea-cup"); console.log(`TeaCup watches: ${TeaCup.observedAttributes.join(", ")}`); cup.size = 5; console.log(`size="${cup.getAttribute("size")}"`);</script>TypeScript calls attribute() with a context object. It keeps the declaration in the class's metadata, and finalize() reads it there.
- Line 1 is a cup with a size of 4 and a dark roast.
- Line 5 prints what the class watches. Lines 6 and 7 set the size to 5, and print the attribute.
Standard decorators print TeaCup watches: size, roast and size="5". So do legacy ones with useDefineForClassFields: false. Legacy with true prints size="4" and the class field error. TypeScript kept size; and roast; as fields. That's why Lit asks for false with legacy decorators.
Open the first choice's tea-cup.js tab. It's long: TypeScript adds two helpers, __esDecorate and __runInitializers. Lit gives that size as the reason it still recommends TypeScript's legacy decorators (Lit). In Lit itself, the cup's size reads like this:
import { LitElement } from "lit";
import { property } from "lit/decorators.js";
class TeaCup extends LitElement {
@property({ type: Number, reflect: true, useDefault: true })
accessor size = 3;
}- Line 5 makes a number that reflects.
useDefaultkeeps the default from becoming an attribute. - Line 6 is an auto-accessor with a starting value. Lit reads that 3 as the default.
Lit 3 was the first Lit to take standard decorators. Older examples, written for legacy decorators, put @property() on a plain field. With standard decorators, they need accessor added (Lit 3 upgrade guide). Lit uses them in full.
How do Lit and Catalyst declare attributes?
The same jobs, done three ways. Read each row across:
| Question | TeaElement | Lit | Catalyst 1.8 |
|---|---|---|---|
| Where do you declare it? | In static attributes, or with @attribute(). | In static properties, or with @property(). | With @attr on a class field. |
| What is the attribute called? | The name with dashes: giftWrapped watches gift-wrapped. | The name in lowercase: giftWrapped watches giftwrapped. | data- and the name with dashes: data-gift-wrapped. |
| Where does the value live? | In a private Map on each element. | Under a hidden symbol key on each element. | In the attribute itself. |
What does size="big" give for a number? | The fallback, by HTML's rules. | NaN, from Number(). | NaN, from Number(). |
| When is the attribute written? | In the setter, before it returns. | In the next update, a microtask later. | Always, because the attribute holds the value. |
| What about a class field with the same name? | It throws on connection. | Its development build throws at the first update. | It puts its property on each element, on top of the field. |
Lit
defaultConverterreads a Number withNumber(), a Boolean by presence, and objects and arrays withJSON.parse()(lines 353 to 393).notEqualcompares withObject.is()(lines 403 and 404).- By default, a property is a String with an attribute, and doesn't reflect (lines 406 to 413). The attribute is the name in lowercase (lines 975 to 987).
createProperty()puts the accessor on the prototype (lines 698 to 725).getPropertyDescriptor()builds it: the setter stores the value and asks for an update (lines 754 to 794).- Reflection waits for
update()(lines 1655 to 1662), a microtask after the set.
GitHub's Catalyst
@attris a legacy decorator that only records the name (lines 15 to 17).- When an element connects (core.ts, lines 54 to 58),
initializeAttrs()reads each field's starting value. Its type picks a string, number, or boolean property (lines 39 to 83). - It defines that property on the element itself, on top of the field (line 78). It writes the starting value into the attribute when the page left it out (lines 79 to 81).
- Names get a
data-prefix and dashes (line 43 and line 47).
Each choice has a reason. Catalyst's attribute is the only place the value lives, so nothing can drift. Lit keeps values as given and reflects once per update. TeaElement copies built-in elements: bad text falls back, and the attribute is written at once.
Adding declared attributes to the tea kit
The kit gets declared attributes in kitAfter192:
- tea-kit/element.js:
TeaElement, as this lesson built it, with comments. - tea-kit/converters.js (new helper):
converterFor(). - tea-kit/tea-cup.js (new): the cup, with the kit's tokens and layers.
- tea-kit/tea-price.js: two declared attributes in place of four hand-written accessors.
- tea-kit/custom-elements.json: the new members of element.js, and the two new modules.
Here is the price now:
import { TeaElement } from "./element.js";
export class TeaPrice extends TeaElement {
static attributes = {
amount: { reflect: true },
currency: { reflect: true },
};
createRenderRoot() {
return this;
}
render() {
const currency = this.currency ?? "";
this.textContent = `Price: ${this.amount} ${currency}`.trim();
}
}
customElements.define("tea-price", TeaPrice);- Lines 4 to 7 declare
amountandcurrency, as text that reflects. They replace lesson 19.1's four accessors. - Line 15 reads them through the generated properties.
Why text, and not a Number? A price like 4.50 keeps its zero as text. As a number, it would come back as 4.5. Now both together:
<link rel="stylesheet" href="tea-kit/tokens.css"><p><tea-cup size="4" roast="dark">Hojicha</tea-cup> <tea-price amount="4.50" currency="EUR"></tea-price></p><script type="module"> import "./tea-kit/index.js"; const cup = document.querySelector("tea-cup"); const price = document.querySelector("tea-price"); console.log(`cup.size: ${cup.size}, a ${typeof cup.size}`); console.log(`price.amount: ${price.amount}, a ${typeof price.amount}`);</script>Lines 7 and 8 print cup.size: 4, a number and price.amount: 4.50, a string. The price shows the same text as before, and keeps a value set before the kit loads. One change for kit authors: only declared attributes get that early-value treatment now. Declare an attribute if code may set its property early.
Common mix-ups
- "attributeChangedCallback() runs for every attribute." No. It runs only for names in
observedAttributes, whichTeaElementbuilds from the declarations. - "iced="false" turns a boolean attribute off." No. Any text means on. Remove the attribute, or set the property to false.
- "Reflect every property, so the HTML shows the state." No. Each change writes the HTML and runs the callback. Reflect settings and styling hooks, and use
:state()for internal state. - "A class field is a fine place for a default." No. It hides the generated property. Give the default as
fallback. - "Decorators run in browsers now." No. They're a stage 2.7 proposal, Chrome throws a
SyntaxError, and TypeScript or Babel compiles them. - "Examples for legacy decorators work with standard ones." No. Standard decorators need
accessoron the field. - "Lit's Number converter gives a default for bad text." No. It uses
Number(), sobiggivesNaN. - "Only objects and dates need the reflection guard." No.
TeaElement's setter writes the attribute every time, so even a number loops without it.
Practice exercises
The cup says size="2.5 cups" and roast="DARK". Predict what the page prints, then run it.
<tea-cup size="2.5 cups" roast="DARK">Oolong</tea-cup><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); console.log(cup.size, cup.roast);</script><tea-cup size="2.5 cups" roast="DARK">Oolong</tea-cup><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); console.log(cup.size, cup.roast);</script>It prints 2.5 dark. toFloat() reads 2.5 and stops at the space. toKeyword() lowercases DARK, which is a keyword.
The cup says iced="false". Then the script sets cup.iced = false. What does the page print?
<tea-cup iced="false">Sencha</tea-cup><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); const before = cup.iced; cup.iced = false; console.log(before, cup.iced, cup.hasAttribute("iced"));</script><tea-cup iced="false">Sencha</tea-cup><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); const before = cup.iced; cup.iced = false; console.log(before, cup.iced, cup.hasAttribute("iced"));</script>It prints true false false. The attribute was there, so iced started true. Setting false removed the attribute, because iced reflects.
Fill in static attributes in the tea-order.js tab. Then press One more sugar once. What does the order show?
<p><tea-order strength="STRONG" sugar="two">Chai</tea-order></p><button id="sugar">One more sugar</button><script type="module"> import "./tea-order.js"; const order = document.querySelector("tea-order"); document.querySelector("#sugar").addEventListener("click", () => { order.sugar += 1; });</script><p><tea-order strength="STRONG" sugar="two">Chai</tea-order></p><button id="sugar">One more sugar</button><script type="module"> import "./tea-order.js"; const order = document.querySelector("tea-order"); document.querySelector("#sugar").addEventListener("click", () => { order.sugar += 1; });</script>Only the tea-order.js tab changes: it declares strength with values and a fallback, and sugar as a reflecting number. STRONG becomes strong, two becomes 0, and one press makes 1.
Press Not iced. The cup still says iced, and the page reports an error. Fix the tea-cup.js tab. What does the cup show after the press then?
<p><tea-cup iced size="2">Matcha</tea-cup></p><button id="warm">Not iced</button><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); document.querySelector("#warm").addEventListener("click", () => { cup.iced = false; });</script><p><tea-cup iced size="2">Matcha</tea-cup></p><button id="warm">Not iced</button><script type="module"> import "./tea-cup.js"; const cup = document.querySelector("tea-cup"); document.querySelector("#warm").addEventListener("click", () => { cup.iced = false; });</script>Only the tea-cup.js tab changes: the class field on line 14 goes. Then the generated setter runs, removes the attribute, and the cup draws again without iced.
The tasting cup's converter in the tasting-cup.js tab hands text through as it is. Make flavors a list of words, like the class attribute. What does the page print after one press of Add sweet?
<p><tasting-cup flavors="malty smoky">Assam</tasting-cup></p><button id="sweet">Add sweet</button><script type="module"> import "./tasting-cup.js"; const cup = document.querySelector("tasting-cup"); console.log(`${cup.flavors.length} flavors`); document.querySelector("#sweet").addEventListener("click", () => { cup.flavors = [...cup.flavors, "sweet"]; console.log(cup.getAttribute("flavors")); });</script><p><tasting-cup flavors="malty smoky">Assam</tasting-cup></p><button id="sweet">Add sweet</button><script type="module"> import "./tasting-cup.js"; const cup = document.querySelector("tasting-cup"); console.log(`${cup.flavors.length} flavors`); document.querySelector("#sweet").addEventListener("click", () => { cup.flavors = [...cup.flavors, "sweet"]; console.log(cup.getAttribute("flavors")); });</script>Only the tasting-cup.js tab changes: fromAttribute() splits the text into words, and toAttribute() joins them with spaces. The page prints 2 flavors, then malty smoky sweet.
The cup declares max: 5 for size, and says size="9". Add the option to the converters.js tab, so a bigger number counts as the max. What does the page print?
<p><tea-cup size="9">Sencha</tea-cup></p><script type="module"> import "./tea-cup.js"; console.log(document.querySelector("tea-cup").size);</script><p><tea-cup size="9">Sencha</tea-cup></p><script type="module"> import "./tea-cup.js"; console.log(document.querySelector("tea-cup").size);</script>Only the converters.js tab changes: converterFor() reads max, and the number converter gives Math.min(value, max), keeping null. The cup declares max: 5, so size="9" gives 5.
Check your understanding
Question 1 of 7A page has 50 cups. Where does TeaElement put the getter and setter for
size?Choose an answer to see the explanation.
Question 2 of 7The page holds
<tea-cup size="big">. What does this code print?Read the code, then predictJavaScriptconst cup = document.querySelector("tea-cup"); // <tea-cup size="big"> console.log(cup.size, cup.getAttribute("size"));Choose an answer to see the explanation.
Question 3 of 7In what order does this code print its letters?
Read the code, then predictJavaScriptclass TeaTimer extends HTMLElement { static observedAttributes = ["seconds"]; attributeChangedCallback() { console.log("b"); } } customElements.define("tea-timer", TeaTimer); const timer = document.createElement("tea-timer"); console.log("a"); timer.setAttribute("seconds", "60"); console.log("c");Choose an answer to see the explanation.
Question 4 of 7Why does TeaElement's #reflecting check stop the reflection loop?
Choose an answer to see the explanation.
Question 5 of 7A TeaCup subclass writes
size = 2;as a class field. What happens?Choose an answer to see the explanation.
Question 6 of 7Can Chrome run
@attribute({ type: Number }) accessor size;with no build step?Choose an answer to see the explanation.
Question 7 of 7Which of these should a tea cup NOT reflect to an attribute?
Choose an answer to see the explanation.
Key takeaways
- Declare each attribute once, with its type, its default, and whether it reflects.
- finalize() turns the declarations into observedAttributes, a map by attribute name, and one property each.
- createProperty() puts a getter and a setter on the prototype. Each element keeps its values in a private Map.
- A class field hides a generated property. Give defaults as fallback instead.
- Converters read text with HTML's rules and a fallback. A setter sends values through the same rules.
- The callback runs inside setAttribute(), so one #reflecting mark stops the loop both ways.
- Bad text gives the default, the attribute keeps its text, and a default never becomes an attribute.
- Decorators declare the same thing, but need TypeScript or Babel: no browser runs them yet.
Remember the one-liner.
Say what each attribute is once, and let the base class keep the property and the attribute in step.
Sources
The facts on this page come from these docs, posts, specifications, and source files:
- Using custom elements: responding to attribute changes, MDN.
- Attribute reflection, MDN.
- Reactive properties, Lit.
- Object.defineProperty(), MDN.
- Handling properties in custom element upgrades, Nolan Lawson.
- TSConfig reference: useDefineForClassFields, TypeScript.
- HTML attributes vs DOM properties, Jake Archibald.
- HTML Standard: custom element reactions, WHATWG.
- Bulletproof Web Component APIs, Burton Smith.
- Reflection and Custom States in Web Components, Cory LaViska.
- Tutorial: custom attribute converters, Lit.
- Decorators, Lit.
- Lit 3 upgrade guide, Lit.
- Decorators proposal, TC39.
- Decorators, Can I use.
- reactive-element.ts, at Lit 3.3.3, Lit.
- decorators/property.ts, at Lit 3.3.3, Lit.
- CHANGELOG.md for lit, at Lit 3.3.3, Lit.
- attr.ts, at Catalyst 1.8.1, GitHub.
- core.ts, at Catalyst 1.8.1, GitHub.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Mixins, controllers, and behaviors. Share behavior between components without deep inheritance.