web_dev

Web Components Tutorial: Build Reusable Custom Elements That Work Across All Frameworks

Learn how to build reusable Web Components with Custom Elements, Shadow DOM & HTML Templates. Create portable UI elements that work across all frameworks.

Web Components Tutorial: Build Reusable Custom Elements That Work Across All Frameworks

Implementing Web Components: Techniques for Reusable Custom Elements

Creating reusable UI elements feels like building with digital LEGO. I’ve built countless interfaces where components needed to work across different tech stacks. Web Components solve this by providing native browser standards for creating encapsulated elements. They work everywhere without framework dependencies.

The core consists of three technologies: Custom Elements for defining new HTML tags, Shadow DOM for style isolation, and HTML Templates for reusable markup patterns. When combined, they create self-contained UI pieces that behave like native HTML elements.

Let me show you a practical example. This user card component accepts name and avatar attributes:

class InteractiveCard extends HTMLElement {
  static observedAttributes = ['name', 'avatar'];
  
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>
        :host {
          display: inline-block;
          border-radius: 12px;
          overflow: hidden;
          box-shadow: 0 4px 8px rgba(0,0,0,0.1);
          transition: transform 0.2s;
          background: white;
        }
        :host(:hover) {
          transform: translateY(-5px);
        }
        .card-content {
          padding: 20px;
          text-align: center;
        }
        img {
          width: 100%;
          max-height: 200px;
          object-fit: cover;
        }
      </style>
      <div class="card-content">
        <img src="" alt="Profile image">
        <h3></h3>
        <slot name="description"></slot>
      </div>
    `;
  }

  connectedCallback() {
    this.updateContent();
    this.addEventListener('click', this.handleClick);
  }

  attributeChangedCallback(name, oldVal, newVal) {
    if (oldVal !== newVal) this.updateContent();
  }

  handleClick = () => {
    this.dispatchEvent(new CustomEvent('card-selected', {
      detail: { user: this.getAttribute('name') },
      bubbles: true
    }));
  };

  updateContent() {
    this.shadowRoot.querySelector('h3').textContent = 
      this.getAttribute('name') || 'Guest';
    this.shadowRoot.querySelector('img').src = 
      this.getAttribute('avatar') || 'default.jpg';
  }
}

customElements.define('interactive-card', InteractiveCard);
<interactive-card 
  name="Taylor Reed" 
  avatar="taylor-profile.jpg"
>
  <p slot="description">UX Designer & Frontend Developer</p>
</interactive-card>

This component demonstrates several key features. The Shadow DOM encapsulates styles so they won’t leak out. Attributes automatically update the content when changed. The <slot> element enables content projection. I’ve added a custom event that bubbles up when users click the card.

For state management, I prefer using properties instead of attributes for complex data. Here’s how I handle JSON data:

class DataCard extends HTMLElement {
  #userData = null;

  set user(value) {
    this.#userData = value;
    this.render();
  }

  get user() {
    return this.#userData;
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  render() {
    if (!this.#userData) return;
    
    this.shadowRoot.innerHTML = `
      <div class="profile">
        <h2>${this.#userData.name}</h2>
        <p>Joined: ${new Date(this.#userData.joinDate).toLocaleDateString()}</p>
      </div>
    `;
  }
}

// Usage
const card = document.querySelector('data-card');
card.user = { name: 'Jamie Smith', joinDate: '2023-06-15' };

Notice the private class field #userData for true encapsulation. The render method updates only when data changes. This pattern scales well for complex components.

Integrating with frameworks is straightforward. For React:

function ReactWrapper() {
  const ref = useRef(null);
  
  useEffect(() => {
    ref.current.addEventListener('card-selected', handleEvent);
    return () => ref.current.removeEventListener('card-selected', handleEvent);
  }, []);

  return <interactive-card ref={ref} name="Alex" avatar="alex.jpg" />;
}

In Vue:

<template>
  <interactive-card 
    ref="card" 
    name="Sam" 
    avatar="sam.png" 
    @card-selected="handleSelect"
  />
</template>

Angular requires a small wrapper:

@Component({
  selector: 'app-card',
  template: `<interactive-card [name]="name" [avatar]="avatar"></interactive-card>`
})
export class CardComponent {
  @Input() name: string;
  @Input() avatar: string;
}

Accessibility is crucial. I always add ARIA attributes in the constructor:

constructor() {
  super();
  this.attachShadow({ mode: 'open' });
  this.setAttribute('role', 'article');
  this.setAttribute('aria-labelledby', 'card-title');
}

For progressive enhancement, I use feature detection:

if ('customElements' in window) {
  customElements.define('enhanced-card', EnhancedCard);
} else {
  // Fallback to basic div structure
  document.querySelectorAll('basic-card').forEach(el => {
    el.innerHTML = `<div class="basic-card">${el.innerHTML}</div>`;
  });
}

Lifecycle hooks help manage resources. I use disconnectedCallback for cleanup:

disconnectedCallback() {
  this.removeEventListener('click', this.handleClick);
  clearInterval(this.#updateInterval);
}

When designing components, I follow these principles:

  • Keep element names hyphenated (my-custom-element)
  • Extend existing elements when possible
  • Prefer declarative attributes for initial setup
  • Use properties for runtime state changes
  • Implement accessibility from day one
  • Provide CSS custom properties for theming

Web Components work best when they feel native. I test them across browsers and ensure they degrade gracefully. The web platform continues evolving, but these patterns provide lasting value. Components built this way outlive framework trends.

Remember to test performance with many instances. I optimize by sharing templates:

const template = document.createElement('template');
template.innerHTML = `
  <style>/* Shared styles */</style>
  <div class="container"></div>
`;

class EfficientElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

This approach clones pre-parsed DOM instead of re-parsing HTML strings. For complex projects, I use lit-html for efficient updates.

Web Components enable true UI portability. I’ve used the same date picker in Vue dashboards, React admin panels, and static marketing sites. They reduce dependency friction and simplify design systems. Start small with simple components and gradually add complexity as needed.

Keywords: web components, custom elements, shadow dom, html templates, reusable ui components, web component development, custom html elements, shadow dom encapsulation, html templates javascript, web components tutorial, creating custom elements, web component lifecycle, custom element attributes, web component events, slot element, web component styling, css custom properties, web component accessibility, progressive enhancement, web components react, web components vue, web components angular, custom element lifecycle hooks, web component best practices, native web components, browser standards, component encapsulation, reusable web elements, custom element api, web component patterns, javascript custom elements, html5 custom elements, web component library, custom element properties, web component state management, cross framework components, framework agnostic components, web standards, custom element registration, web component performance, lit html, web component templates, component isolation, web component polyfills, custom element callbacks, web component slots, css in js web components, web component architecture, modular web components, web component testing, responsive web components, web component themes, custom element styling, web component events handling, web component data binding



Similar Posts
Blog Image
Is Vite the Secret Weapon Every Web Developer Needs?

Unlocking Vite: Transforming Frontend Development with Speed and Efficiency

Blog Image
Cache Performance Optimization: Proven Strategies to Accelerate Web Application Data Retrieval by 80%

Boost web app performance with strategic caching techniques. Learn cache-aside patterns, memory management, and distributed solutions to cut response times by 80%.

Blog Image
Is Contentful the Game-Changer Your Website Needs?

Riding the Wave of Digital Content Evolution with Contentful's Headless CMS Magic

Blog Image
API Versioning Done Right: Strategies, Code Patterns, and Sunsetting Old Versions

Learn how to version your REST API using URI paths, headers, and content negotiation. Avoid breaking changes and keep clients happy with proven strategies.

Blog Image
Complete Guide: Building International Web Applications - Technical Best Practices 2024

Learn essential strategies and technical implementations for building multilingual web applications. Discover key practices for translation management, RTL support, and localization. Includes code examples and best practices.

Blog Image
Mastering Accessible Web Forms: A Developer's Guide to Inclusive Design

Learn to create accessible web forms. Explore best practices for HTML structure, labeling, error handling, and keyboard navigation. Improve user experience for all, including those with disabilities. Click for expert tips.