Sling Academy
Home/JavaScript/Reuse UI Blocks Across Projects via JavaScript Web Components

Reuse UI Blocks Across Projects via JavaScript Web Components

Last updated: December 13, 2024

In modern frontend development, maintaining consistency across multiple projects can be a challenge. JavaScript Web Components offer a standardized way to make UI elements reusable, ensuring that your user interface remains consistent across your projects. In this article, we'll learn how to build reusable UI blocks using Web Components and integrate them across various projects.

Introduction to Web Components

Web Components is a powerful suite of standardized features that let developers create custom, encapsulated HTML elements. They consist of the following key specifications:

  • Custom Elements: APIs allowing the definition of new HTML tags.
  • Shadow DOM: A mechanism to encapsulate styles and markup, isolating them from the global DOM.
  • HTML Templates: Reusable templates that can be inserted into documents.

Creating a Basic Web Component

Let’s start by creating a simple web component. We’ll make a custom button element using Web Components.

// Define a class for the new element
class MyButton extends HTMLElement {
  constructor() {
    super();
    // Attach a shadow root to the element.
    const shadow = this.attachShadow({mode: 'open'});

    // Create the button element
    const button = document.createElement('button');
    button.textContent = 'Click me!';

    // Append the button to the shadow DOM
    shadow.appendChild(button);
  }
}

// Register the new element with the browser.
customElements.define('my-button', MyButton);

Here, we've created a basic web component, my-button, that renders a button element within its shadow DOM.

Using HTML Templates

Next, we'll create and use an HTML template within our web component to separate markup from scripting logic.

class StyledButton extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({mode: 'open'});
    
    // Using a template
    const template = document.createElement('template');
    template.innerHTML = `
      <style>
        button { 
          background-color: #008CBA; 
          color: white; 
          border: none;
          cursor: pointer;
          padding: 15px 32px;
          font-size: 16px;
        }
      </style>
      <button>Styled Button</button>
    `;
    
    // Apply the template content to the shadow DOM
    shadow.appendChild(template.content.cloneNode(true));
  }
}

customElements.define('styled-button', StyledButton);

Here, an HTML template is used to define the styles and structure, allowing us to reuse and maintain the markup more efficiently.

Distributing the Web Component

One of the great advantages of Web Components is their portability. To use your web components across different projects:

  1. Bundle your component: Use a bundler like Webpack or Rollup for packaging.
  2. Register your component in npm: This way, you can easily share it as a module.
  3. Use CDNs: Serving your components over a CDN allows for quick imports without local dependencies.

To distribute, consider the following example for exporting and importing a web component module:

// Exposing your custom element module
// my-button.js
export default customElements.define('my-button', MyButton);

// Importing and using in another project
import 'url_of_your_cdn_or_module_location/my-button.js';

Conclusion

Web Components provide a robust framework for creating reusable UI elements that can be shared across different projects easily. By building encapsulated and portable elements, development teams can enhance productivity, maintain consistency, and reduce code duplication across multiple applications. Start implementing Web Components in your projects today to experience a new level of frontend development efficiency!

Next Article: Create Framework-Agnostic UI Using Web Components in JavaScript

Previous Article: Encapsulate Styles and Logic Using JavaScript Web Components

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration