Skip to Content
Course content

210: Building a Reusable Web Component

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a high-end modular sofa. When you buy one, you aren't buying a pile of fabric, foam, and wooden beams that you have to assemble from scratch every time you move a piece. Instead, you have a "module"—a predefined block that has its own structure, its own padding, and its own connectors. If you want a larger sofa, you don't rebuild the whole thing; you just drop in another identical module. The module doesn't care which room it's in; it just knows how to be a sofa piece.

In JavaScript, a Web Component is exactly that. Instead of copying and pasting the same HTML structure for a user profile or a product card across ten different pages, you create a custom HTML tag—like <user-card>—that carries its own logic, styles, and structure wherever it goes.

Mapping the module to the code

To build this, we use a few specific tools that map directly to our modular sofa analogy:

  • The Blueprint (The Class): Just as a manufacturer has a blueprint for the sofa module, we create a JavaScript class that extends HTMLElement. This tells the browser, "This isn't just a random object; it's a piece of the DOM."
  • The Enclosure (Shadow DOM): You wouldn't want the fabric of your sofa to magically merge with the carpet of your living room. The Shadow DOM creates a "capsule" around your component. The CSS inside the component stays inside; it won't leak out and accidentally turn every paragraph on your page blue.
  • The Assembly (connectedCallback): This is the moment the module is actually placed in the room. In code, this is the lifecycle method that triggers as soon as the element is appended to the document.

Building a living User Profile Card

I've found that the best way to grasp this is to build something you'll actually use. Let's make a <user-profile> component. I want this to take a name and a role via attributes and render them beautifully without affecting the rest of the page's styles.

class UserProfile extends HTMLElement {
  constructor() {
    super();
    // We create the 'capsule' here so our styles are isolated
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    const name = this.getAttribute('name') || 'Unknown User';
    const role = this.getAttribute('role') || 'Guest';

    this.shadowRoot.innerHTML = `
      
      
${name} ${role}
`; } } // This is where we tell the browser: "Whenever you see <user-profile>, use this class." customElements.define('user-profile', UserProfile);

Why this beats a template literal

You might be thinking, "Can't I just write a function that returns a string of HTML?" Sure, you can. But by using a formal Web Component, you get something much more powerful. You can now use this in your HTML just like a native tag: <user-profile name="Sarah" role="Lead Engineer"></user-profile>.

Because it's a real element, you can attach event listeners to it, style it from the outside (via CSS variables), and most importantly, you can move it between different frameworks or plain HTML files without rewriting the logic. It's a truly portable piece of UI.




📋 Practical Task

Build a Dynamic Product Price Tag Component

Your goal is to create a reusable Web Component called <price-tag>. This component should be used to display the price of an item in an e-commerce store.

Requirements:

  • The component must accept two attributes: amount (e.g., "49.99") and currency (e.g., "USD" or "EUR").
  • Use the Shadow DOM to ensure the styles don't leak.
  • The style should include a background color, a specific font-weight for the amount, and some padding to make it look like a badge.
  • If the currency attribute is missing, it should default to "USD".
  • Register the component so it can be used as <price-tag></price-tag> in the HTML.

Test your work by adding this to your HTML:
<price-tag amount="25.00" currency="GBP"></price-tag>

Rating
0 0

There are no comments for now.

to be the first to leave a comment.