Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Web Components: Custom Elements, Shadow DOM and Reusable UI

How can a UI component be shared without depending on one framework? Web Components provide browser-native building blocks, not a complete application architecture. A quantity counter illustrates a stable contract, accessible interaction and testing across component boundaries.

Published Written by Reading time 15 min read
On this page Contents: quick navigation between sections

When should you use Web Components?

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Quantity component</title>
    <link rel="stylesheet" href="/en/demo.css" />
    <script type="module" src="demo.js"></script>
  </head>
  <body>
    <main>
      <h1>Quantity</h1>
      <pp-quantity value="2"></pp-quantity>
      <noscript>Changing the quantity requires JavaScript.</noscript>
    </main>
  </body>
</html>

demo.ts

import { registerQuantity } from "./quantity-element.js";

registerQuantity();

Related article: Semantic HTML.

Custom Elements register new HTML tags, Shadow DOM encapsulates a tree and most CSS selectors, and template and slot separate structure from supplied content. You do not need all three. Choose an autonomous element with a hyphenated name such as pp-quantity. This is useful for libraries shared across applications.

For a simple button, form input or component confined to one framework, native HTML or a framework component is often simpler. The example counter is not a form control. [1][2][3][4]

Registration and lifecycle

quantity-element.ts

import {
  isQuantity,
  MAX_QUANTITY,
  MIN_QUANTITY,
  parseQuantity,
  stepQuantity,
} from "./quantity.js";
import { createQuantityView } from "./quantity-view.js";
import type { QuantityView } from "./quantity-view.js";

export const QUANTITY_TAG = "pp-quantity";
export const QUANTITY_CHANGE = "quantity-change";

export interface QuantityChangeDetail {
  readonly value: number;
}

export class QuantityElement extends HTMLElement {
  static readonly observedAttributes = ["value"];

  private readonly view: QuantityView;
  private listeners: AbortController | undefined;

  constructor() {
    super();
    const root = this.attachShadow({ mode: "open" });
    this.view = createQuantityView(root);
  }

  get value(): number {
    return parseQuantity(this.getAttribute("value"));
  }

  set value(value: number) {
    if (!isQuantity(value)) {
      throw new RangeError("Invalid quantity.");
    }

    this.setAttribute("value", String(value));
  }

  connectedCallback(): void {
    if (!this.isConnected) {
      return;
    }

    this.upgradeValue();
    this.render();
    this.listeners?.abort();
    this.listeners = new AbortController();

    const options = { signal: this.listeners.signal };
    this.view.decrease.addEventListener("click", this.decrease, options);
    this.view.increase.addEventListener("click", this.increase, options);
  }

  disconnectedCallback(): void {
    this.listeners?.abort();
    this.listeners = undefined;
  }

  attributeChangedCallback(): void {
    this.render();
  }

  private upgradeValue(): void {
    if (!Object.hasOwn(this, "value")) {
      return;
    }

    const previous: unknown = Reflect.get(this, "value");

    if (!Reflect.deleteProperty(this, "value")) {
      throw new TypeError("Cannot upgrade value property.");
    }

    if (isQuantity(previous)) {
      this.value = previous;
    }
  }

  private readonly decrease = (): void => {
    this.change(-1);
  };

  private readonly increase = (): void => {
    this.change(1);
  };

  private change(step: -1 | 1): void {
    const current = this.value;
    const next = stepQuantity(current, step);

    if (next === current) {
      return;
    }

    this.value = next;
    this.dispatchEvent(
      new CustomEvent<QuantityChangeDetail>(QUANTITY_CHANGE, {
        detail: { value: next },
        bubbles: true,
        composed: true,
      }),
    );
  }

  private render(): void {
    const value = parseQuantity(this.getAttribute("value"));
    this.view.output.value = String(value);
    this.view.decrease.setAttribute(
      "aria-disabled",
      String(value === MIN_QUANTITY),
    );
    this.view.increase.setAttribute(
      "aria-disabled",
      String(value === MAX_QUANTITY),
    );
  }
}

export function registerQuantity(): void {
  const existing = customElements.get(QUANTITY_TAG);

  if (existing === QuantityElement) {
    return;
  }

  if (existing !== undefined) {
    throw new Error(`Custom element already registered: ${QUANTITY_TAG}`);
  }

  customElements.define(QUANTITY_TAG, QuantityElement);
}

declare global {
  interface HTMLElementTagNameMap {
    "pp-quantity": QuantityElement;
  }
}

The constructor prepares the internal tree without relying on host attributes or children being available. connectedCallback can run again when an element is moved or reinserted; disconnectedCallback releases resources. Attributes listed in observedAttributes trigger attributeChangedCallback, including when existing elements are upgraded.

A global registry name cannot be overwritten with another definition. The registration function ignores repeated registration of the same class and rejects collisions. Import the module extending HTMLElement only in a browser environment. [2]

Registration and readiness differ. whenDefined() waits for the definition, not for data loaded by a component. upgrade() can upgrade a detached subtree. Ordinary moves can still disconnect and reconnect elements; moveBefore() with connectedMoveCallback preserves state when both features are supported. [15][16][17]

Attributes, properties and validation

quantity.ts

export const MIN_QUANTITY = 0;
export const MAX_QUANTITY = 99;

export function isQuantity(value: unknown): value is number {
  if (typeof value !== "number") {
    return false;
  }

  if (!Number.isSafeInteger(value)) {
    return false;
  }

  if (value < MIN_QUANTITY) {
    return false;
  }

  return value <= MAX_QUANTITY;
}

export function parseQuantity(raw: string | null): number {
  if (raw === null) {
    return MIN_QUANTITY;
  }

  if (!/^\d{1,2}$/.test(raw)) {
    return MIN_QUANTITY;
  }

  const value = Number(raw);

  if (String(value) !== raw) {
    return MIN_QUANTITY;
  }

  return isQuantity(value) ? value : MIN_QUANTITY;
}

export function stepQuantity(value: number, step: -1 | 1): number {
  if (!isQuantity(value)) {
    throw new RangeError("Invalid quantity.");
  }

  switch (step) {
    case -1:
      return Math.max(MIN_QUANTITY, value - 1);
    case 1:
      return Math.min(MAX_QUANTITY, value + 1);
    default:
      throw new RangeError("Invalid step.");
  }
}

An attribute contains text or is absent; a JavaScript property can hold numbers and objects. The value attribute accepts a canonical integer from 0 through 99, with missing or invalid text interpreted as 0. The setter rejects invalid numbers and reflects valid ones to the attribute.

Rendering never writes that attribute again. An own property assigned before registration can hide the prototype setter. The example recovers a valid value on connection and otherwise uses the attribute. For an upgraded detached element, this recovery occurs when it is connected. [2]

Treat Boolean attributes such as required by presence, not text: required="false" still enables the option. Remove the attribute to turn it off. [18]

Shadow DOM, templates and slots

quantity-view.ts

export interface QuantityView {
  decrease: HTMLButtonElement;
  increase: HTMLButtonElement;
  output: HTMLOutputElement;
}

function createButton(label: string, text: string): HTMLButtonElement {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = text;
  button.setAttribute("aria-label", label);
  button.setAttribute("part", "button");

  return button;
}

export function createQuantityView(root: ShadowRoot): QuantityView {
  const stylesheet = document.createElement("link");
  stylesheet.rel = "stylesheet";
  stylesheet.href = new URL("./quantity.css", import.meta.url).href;

  const group = document.createElement("div");
  group.className = "quantity";
  group.setAttribute("role", "group");
  group.setAttribute("aria-label", "Quantity");

  const decrease = createButton("Decrease quantity", "−");
  const increase = createButton("Increase quantity", "+");
  const output = document.createElement("output");
  output.setAttribute("part", "value");
  output.setAttribute("aria-label", "Current quantity");

  group.append(decrease, output, increase);
  root.append(stylesheet, group);

  return { decrease, increase, output };
}

slot-demo.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Declarative Shadow DOM and slots</title>
  </head>
  <body>
    <main>
      <div id="panel">
        <template shadowrootmode="open">
          <section>
            <h2><slot name="heading">Summary</slot></h2>
            <slot>No details available.</slot>
          </section>
        </template>
        <span slot="heading">Order summary</span>
        <p>Two items in the order.</p>
      </div>
    </main>
  </body>
</html>

Open mode exposes shadowRoot; closed mode limits conventional access from the host but is not a security boundary. Page selectors generally do not select internal nodes, although inherited properties and CSS tokens may cross the boundary. A template stores inert markup for cloning, and a slot presents matching host children.

Assigned nodes still belong to the light DOM. slotchange reports changes to assigned nodes, not every change to their contents. The counter constructs its internal tree with DOM APIs so data is not interpreted as HTML. [3][4]

The separate example below declares a shadow tree with a named and a default slot. Without assigned nodes, the slot shows its fallback content. Assignment does not move nodes into the shadow tree. [3][4][19]

Events and accessibility

Related article: Event Bubbling, Capturing and Delegation.

quantity-change is dispatched only after a real change triggered by button activation, not a property assignment. bubbles enables delegation and composed permits crossing a shadow boundary, including when the host is nested in another shadow tree. Consumers should not rely on the internal event.target because retargeting applies.

Native type=button controls have explicit accessible names, and output presents the result. To retain focus at a boundary, the counter uses aria-disabled instead of disabled. This attribute does not suppress activation: the change function clamps the range and emits no event when the value remains unchanged. A different border style signals unavailability without relying only on color. Test keyboard operation, contrast, focus and screen-reader announcements. Semantics alone cannot establish WCAG conformance. [5][6][20]

Styling and forms

quantity.css

:host {
  display: inline-block;
  color: var(--quantity-text, #172033);
}

.quantity {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

button {
  min-width: 44px;
  min-height: 44px;
  border: 1px solid currentColor;
  border-radius: 0.5rem;
  background: var(--quantity-surface, #ffffff);
  color: inherit;
  font: inherit;
  cursor: pointer;
}

button:focus-visible {
  outline: 3px solid var(--quantity-focus, #174cc9);
  outline-offset: 3px;
}

button[aria-disabled="true"] {
  border-style: dashed;
  cursor: default;
}

output {
  min-width: 3ch;
  text-align: center;
  font-variant-numeric: tabular-nums;
}

demo.css

body {
  font: 1rem/1.6 system-ui, sans-serif;
  padding: 2rem;
}

pp-quantity {
  --quantity-text: #172033;
  --quantity-surface: #f5f7fb;
  --quantity-focus: #174cc9;
}

pp-quantity::part(button) {
  border-radius: 0.75rem;
}

Related article: CSS Variables and Themes.

Shared CSS tokens and ::part provide a public styling contract instead of exposing private class names. The stylesheet is a separate resource; loading can briefly leave the component unstyled. Prefer a native input for actual form fields. A custom element can participate in forms with static formAssociated, attachInternals, setFormValue and setValidity, but must also handle reset, disabled state and restoration.

The example counter does not automatically contribute to FormData. Validate submitted values and limits on the server too. [7][8][13][14]

Form-associated controls with ElementInternals

consent-element.ts

const CONSENT_TAG = "pp-consent";
const CHECKED_STATE = "checked";
const UNCHECKED_STATE = "unchecked";
const SUBMISSION_VALUE = "yes";

export class ConsentElement extends HTMLElement {
  static readonly formAssociated = true;
  static readonly observedAttributes = ["checked", "required"];

  private readonly internals: ElementInternals;
  private readonly input: HTMLInputElement;
  private listeners: AbortController | undefined;

  constructor() {
    super();
    this.internals = this.attachInternals();
    const root = this.attachShadow({ mode: "open" });
    const label = document.createElement("label");
    this.input = document.createElement("input");
    this.input.type = "checkbox";
    label.append(this.input, " Accept terms");
    root.append(label);
  }

  connectedCallback(): void {
    if (!this.isConnected) {
      return;
    }

    this.syncForm();
    this.listeners?.abort();
    this.listeners = new AbortController();
    this.input.addEventListener("change", this.handleChange, {
      signal: this.listeners.signal,
    });
  }

  disconnectedCallback(): void {
    this.listeners?.abort();
    this.listeners = undefined;
  }

  attributeChangedCallback(name: string): void {
    if (name === "checked") {
      this.input.checked = this.hasAttribute("checked");
    }

    this.syncForm();
  }

  formDisabledCallback(disabled: boolean): void {
    this.input.disabled = disabled;
  }

  formResetCallback(): void {
    this.input.checked = this.hasAttribute("checked");
    this.syncForm();
  }

  formStateRestoreCallback(state: unknown): void {
    switch (state) {
      case CHECKED_STATE:
        this.input.checked = true;
        break;
      case UNCHECKED_STATE:
        this.input.checked = false;
        break;
      default:
        return;
    }

    this.syncForm();
  }

  private readonly handleChange = (): void => {
    this.syncForm();
  };

  private syncForm(): void {
    this.input.required = this.hasAttribute("required");

    if (this.input.checked) {
      this.internals.setFormValue(SUBMISSION_VALUE, CHECKED_STATE);
      this.internals.setValidity({});
      return;
    }

    this.internals.setFormValue(null, UNCHECKED_STATE);

    if (!this.input.required) {
      this.internals.setValidity({});
      return;
    }

    this.internals.setValidity(
      { valueMissing: true },
      "Accept the terms to continue.",
      this.input,
    );
  }
}

export function registerConsent(): void {
  const existing = customElements.get(CONSENT_TAG);

  if (existing === ConsentElement) {
    return;
  }

  if (existing !== undefined) {
    throw new Error(`Custom element already registered: ${CONSENT_TAG}`);
  }

  customElements.define(CONSENT_TAG, ConsentElement);
}

consent-demo.ts

import { registerConsent } from "./consent-element.js";

registerConsent();

consent-demo.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Form-associated custom element</title>
    <link rel="stylesheet" href="/en/demo.css" />
    <script type="module" src="consent-demo.js"></script>
  </head>
  <body>
    <main>
      <h1>Consent</h1>
      <form method="get">
        <fieldset>
          <legend>Terms</legend>
          <pp-consent name="consent" required></pp-consent>
        </fieldset>
        <button type="submit">Continue</button>
        <button type="reset">Reset</button>
      </form>
    </main>
  </body>
</html>

HTML Forms: Validation and Accessibility.

The counter remains a standalone widget. A separate pp-consent example demonstrates a form-associated consent control. A native checkbox inside a label supplies basic semantics and keyboard interaction. When checked, it submits yes under the host's name; when unchecked, setFormValue(null, state) excludes it from submission. Restoration state is a separate argument, not the submitted value. [8][14][21]

The presence of required requires a check; setValidity sets valueMissing and anchors the message to the inner input. Reset returns to the checked attribute's state. In this specific contract, changing that attribute also changes the current state. formDisabledCallback handles disabling through an ancestor fieldset, and formStateRestoreCallback recognizes saved states. This is a limited example, not a complete native input replacement: it exposes neither a public checked property nor a custom change event, and a native alternative is needed when the API is unavailable. In production, still validate on the server and test error announcements with screen readers. [21][22]

React, Vue, Angular and SSR

React 19 supports custom elements: on the client it assigns existing properties and otherwise uses attributes; during SSR values unsuitable for attributes are omitted according to React's rules. Vue can configure isCustomElement in its template compiler; Angular provides CUSTOM_ELEMENTS_SCHEMA.

Each adapter should explicitly type properties and events. Declarative Shadow DOM lets servers deliver a tree using template shadowrootmode. Do not unconditionally call attachShadow during hydration of an existing declarative tree: matching modes can clear its content.

This demo is client-only; SSR requires a separate strategy to attach behavior to existing nodes. [9][10][11][12]

In React 19, register the definition before rendering if object-valued properties are expected. On the server, strings, numbers and true can become attributes; objects, functions, symbols and false are omitted. Configure isCustomElement at Vue template compilation, and do not treat Angular's CUSTOM_ELEMENTS_SCHEMA as a substitute for a typed contract. [10][11][12]

Testing and versioning

quantity.test.mjs

import assert from "node:assert/strict";
import { test } from "node:test";
import {
  isQuantity,
  parseQuantity,
  stepQuantity,
} from "./dist/quantity.js";

test("accepts integer boundaries", () => {
  // Given
  const values = [0, 99];

  // When
  const results = values.map(isQuantity);

  // Then
  assert.deepEqual(results, [true, true]);
});

test("rejects invalid values", () => {
  const values = [-1, 100, NaN, Infinity, 1.5, "2", null, {}];

  assert.deepEqual(values.map(isQuantity), values.map(() => false));
});

test("parses canonical attributes", () => {
  assert.equal(parseQuantity("2"), 2);
  assert.equal(parseQuantity("99"), 99);
});

test("falls back for malformed attributes", () => {
  const values = [null, "", "02", "2\n", "2.5", " 2", "1e1", "100"];

  assert.deepEqual(values.map(parseQuantity), values.map(() => 0));
});

test("does not cross the lower bound", () => {
  assert.equal(stepQuantity(0, -1), 0);
});

test("does not cross the upper bound", () => {
  assert.equal(stepQuantity(99, 1), 99);
});

test("increments and decrements", () => {
  assert.equal(stepQuantity(3, 1), 4);
  assert.equal(stepQuantity(3, -1), 2);
});

test("rejects invalid starting quantity", () => {
  assert.throws(() => stepQuantity(100, -1), RangeError);
});

test("rejects invalid runtime steps", () => {
  // Given
  const invalidSteps = [0, 2, NaN, "1"];

  // When / Then
  for (const step of invalidSteps) {
    assert.throws(() => stepQuantity(3, step), RangeError);
  }
});

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "Bundler",
    "lib": ["ES2022", "DOM"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "outDir": "dist"
  },
  "include": ["*.ts"]
}

Separate pure counter logic from DOM code to test it in Node.js. Browser checks should cover registration, initial values, events, reconnection, limits, keyboard behavior and consumer integration. Given-When-Then describes the initial state, action and result.

Unit tests do not establish accessibility or browser behavior. Version tag names, attributes, properties, events, slots and CSS parts as public API. Changing event semantics or a part name can be breaking. Test your actual target browsers, not merely the presence of an API. [2]

Form tests should cover an absent FormData entry when unchecked, invalid submission, reset and disabling through a fieldset. Invoking the restoration callback directly tests its logic, not browser-driven restoration after navigation. [21]

Web Components are useful as reusable boundaries across applications when contracts are stable and resources are released. Start with native HTML, use Shadow DOM deliberately and confirm integration in real browsers.

Web Components Custom Elements Shadow DOM TypeScript CSS Accessibility Component Architecture Testing

Frequently asked questions

Is Shadow DOM required?

No. Custom elements can use light DOM when encapsulation is unnecessary.

Does closed Shadow DOM protect secrets?

No. It is encapsulation, not a security boundary.

Are attributes and properties equivalent?

No. Attributes are strings or absent; properties can hold any JavaScript type.

Can custom elements submit form data?

Yes, when designed as form-associated custom elements using the appropriate ElementInternals contract. An ordinary custom element is not sufficient.

Do Web Components replace React or Vue?

No. They provide platform components, while routing, application state and other architecture remain separate decisions.

How do you prevent leaks on reconnection?

Register listeners on connection, release them on disconnection and test repeated attachment.

Does aria-disabled prevent clicks?

No. It conveys unavailability, but code must prevent the action. The counter enforces its range. [20]

Does setFormValue(null) submit an empty value?

No. The control is omitted from form data; an empty string and a missing entry are different. [14][21]

Sources and references

  1. MDN: Web Components↩
  2. MDN: Using custom elements↩1↩2↩3↩4
  3. MDN: Using shadow DOM↩1↩2↩3
  4. MDN: Using templates and slots↩1↩2↩3
  5. MDN: Event.composed↩
  6. MDN: Event.composedPath↩
  7. MDN: CSS shadow parts↩
  8. MDN: ElementInternals↩1↩2
  9. MDN: attachShadow↩
  10. React 19: Custom Elements↩1↩2
  11. Vue: Web Components↩1↩2
  12. Angular: CUSTOM_ELEMENTS_SCHEMA↩1↩2
  13. MDN: Using CSS custom properties↩
  14. MDN: setFormValue↩1↩2↩3
  15. MDN: CustomElementRegistry.whenDefined()↩
  16. MDN: CustomElementRegistry.upgrade()↩
  17. MDN: Element.moveBefore()↩
  18. MDN: Boolean attribute (HTML)↩
  19. MDN: template and declarative Shadow DOM↩
  20. MDN: aria-disabled↩1↩2
  21. WHATWG: HTML Standard, custom elements↩1↩2↩3↩4
  22. MDN: ElementInternals.setValidity()↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning