Web Components: The Future of Modular UI Design

Jul 26, 2024

Have you ever wanted to create reusable JavaScript building blocks that work in any project, no matter what framework others are using? If so, then Web Components might be the solution you're looking for!

This Guide is intended to dive into custom components. Web Components are a collection of tools that expand the web platform. This allows you to define new HTML elements with specific functionality and behavior. 
There’s a lot to think about, and writing a component can require a lot of boilerplate code. Fortunately, some great libraries can make creating custom elements more straightforward, and save you a lot of time and effort.
However, if you’re writing lots and lots of custom elements, using a library can make your code simpler and cleaner, and your workflow more efficient.

What are the Web Components?

That allows developers to create custom, reusable, encapsulated HTML elements.

  • Custom Elements: Enables the creation of new HTML tags.
  • Shadow DOM: Provides encapsulation for custom elements, ensuring that their internal structure and styles do not interfere with the rest of the document.
  • HTML Templates: Allows the definition of HTML templates that can be reused and instantiated in custom elements.

Note: The name of a Web Component needs to contain a dash (-). This naming convention is put into place to enable the HTML parser to distinguish custom from regular elements and also avoid creating your own components that could be added as part of future HTML standards. <mycard></mycard><card></card> or <CardComponent></CardComponent> are all invalid names, while <my-card></my-card> is allowed.

 

Why Web Components?

Web components allow us to take our frontend widgets off this cycle of getting rebuilt in the newest framework flavor

  • Reuse is King: Ever build the same button style ten times? With Web Components, you define a button component once and use it everywhere!
  • Framework Freedom: No more framework lock-in! Web Components work seamlessly with vanilla JavaScript, React, Angular, or any framework you choose.
  • Encapsulation Power: Components keep their styles and functionality isolated, preventing conflicts and promoting cleaner code.

To define a new custom element using the v1 implementation, you simply create a new class that extends HTMLElement using ES6 syntax and register it with the browser:

 

class MyElement extends HTMLElement {...}
window.customElements.define('my-element, MyElement);

//example usage in your app:
<my-element></my-element>


NOTE: Only Chrome V67 and up supports customized built-in elements!

Let's Jump over the example, Building with LitElement.

Certainly! Below is an example of a toggle switch web component using Lit. This example includes the essential parts: defining the component, its styles, and its template.




Code Snippets for User Template:

 

  // component's template
  render() {
    return html`
      <label class="switch">
        <input type="checkbox" .checked="${this.checked}" @change="${this._toggle}">
        <span class="slider"></span>
      </label>
    `;
  }

// Method handler.


  // The toggle handler
  public _toggle(event): void {
    this.checked = event.target.checked;
    this.dispatchEvent(new CustomEvent('toggle', { detail: this.checked }));
  }

Explanation:

  1. We import LitElement and the html function for templating.
  2. We define a AppToggle class that extends LitElement.
  3. We set the name property to accept a string value.
  4. The render method defines how the component looks using LitElement's HTML-like syntax.
  5. Finally, we register the app-toggle custom element.

 

Now, you can use your app-toggle component anywhere in your HTML:

 <div style="display: block; padding:200px">
   <app-toggle name="toggle" checked="true"></app-toggle>
   <app-toggle name="World"></app-toggle>
 </div>


The Future is Modular!

Web Components offer a powerful and versatile approach to building user interfaces. With Reusability, framework independence, and clear separation of concerns, they are poised to be a significant force in the future of web development. So, start building your UI block party with Web Components today!

I have included a screenshot below from WebComponents.org that shows the current browser support - a really nice community guide worth checking out and adding to your Bookmarks:


Conclusion

In this article, you took your first step into the world of web components.

Web components have no third-party dependencies, so using them won't have a big impact on your bundle size. But for more complex components, you may want to reach for a library like Svelte or Lit.

 


 

Poojan Gujarati

About the Author

Poojan Gujarati

I am a Software Engineer at MagnusMinds IT Solution, with over 3 years of professional experience. My expertise includes a variety of frontend technologies such as the Angular Framework, Lit, TypeScript, CSS/SCSS, JavaScript, Ionic, and Cypress.