The Web Components Engineer builds framework-agnostic components using the browser's native Custom Elements API - components that work in React, Vue, Angular, Svelte, or plain HTML without wrapper libraries. The primary use case is a design system or shared component library that must work across multiple teams or technology stacks.
Custom Element Basics
// Vanilla Custom Element - works in every framework
class AlertBanner extends HTMLElement {
static observedAttributes = ['type', 'message'];
connectedCallback() {
this.attachShadow({ mode: 'open' }); // Shadow DOM encapsulation
this.render();
}
attributeChangedCallback() {
if (this.shadowRoot) this.render();
}
render() {
const type = this.getAttribute('type') ?? 'info';
const message = this.getAttribute('message') ?? '';
const colors = { info: '#3b82f6', error: '#ef4444', success: '#22c55e' };
this.shadowRoot!.innerHTML = `
<style>
:host { display: block; }
.banner {
padding: 0.75rem 1rem;
background: ${colors[type as keyof typeof colors] ?? colors.info}22;
border-left: 3px solid ${colors[type as keyof typeof colors] ?? colors.info};
border-radius: 4px;
font-family: system-ui;
}
</style>
<div class="banner" role="alert">${message}</div>
`;
}
}
customElements.define('alert-banner', AlertBanner);
// Usage in any HTML or framework:
// <alert-banner type="error" message="Something went wrong"></alert-banner>
Lit Framework (Recommended)
import { LitElement, html, css } from 'lit';
import { customElement, property } from 'lit/decorators.js';
@customElement('my-button')
class MyButton extends LitElement {
static styles = css`
:host { display: inline-flex; }
button {
padding: 0.5rem 1.25rem;
background: var(--color-primary, #3b82f6);
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
}
button:hover { filter: brightness(1.1); }
`;
@property() label = 'Click me';
@property({ type: Boolean }) disabled = false;
render() {
return html`
<button ?disabled=${this.disabled} @click=${this._handleClick}>
${this.label}
</button>
`;
}
private _handleClick() {
this.dispatchEvent(new CustomEvent('my-click', { bubbles: true, composed: true }));
}
}
Attributes vs Properties
- Attributes - strings only, set in HTML:
<my-el count="5">. Use for simple scalar values, server-rendered HTML, and CSS selectors. - Properties - any JS type, set programmatically:
el.items = [{id: 1}]. Use for arrays, objects, functions. Not visible in HTML source. - Reflect properties to attributes only when you need CSS attribute selectors:
[disabled] - Custom events must have
bubbles: true, composed: trueto cross Shadow DOM boundaries