Skip to content

Creating Web Components

Sid edited this page Mar 20, 2025 · 1 revision

MDN Guide

The MDN Guide to Web Components is a pretty good overview.

Creating a Custom Element with fixed contents

Step 1: Create the class

Paste this into components.js:

class MyCustomElement extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    this.setAttribute("style", "display: contents;");

    this.innerHTML = `
        <!-- HTML for this element -->
      `;
  }
}

Replace MyCustomElement with a sensible name (each word capitalized, no underscores or hyphens), and replace <!-- HTML for this element --> with, well, what it says.

To briefly summarize what this is doing:

  • The first chunk is basically saying "create a new type of HTML element." Our custom element isn't doing anything special, so super(); tells the browser to use the constructor in HTMLElement.
  • connectedCallback() means "When this element is added to the page,"

Note

Why display: contents;? Without it, custom elements seem to ignore the CSS grid that defines our layout. display: contents; tells the browser not to generate a box for our custom element, so other styles and elements behave as though only the innerHTML exists. Here's the CSS spec for display: contents;. Sid's still not completely sure why this is necessary. It probably isn't if you're following best practices for web components, but this seemed like the simplest approach for our project.

Register the new element

At the bottom of components.js,

customElements.define("my-custom-element", MyCustomElement);

Here we're telling the browser, "This is a custom element! If you see a <my-custom-element> tag in our HTML, it's an instance of MyCustomElement.

The name of the new tag must be lowercase and include a hyphen - that's part of the standard. Our other custom elements are named <classname-component>, so stick with that if it makes sense.

For clarity, it's nice to put these lines in the same order as class definitions.

Make a commit now on your feature branch.

Step 2: Test

Pick a file that <my-custom-element> belongs in, and verify that it renders successfully, with exactly the appearance and behavior you were expecting. If your custom element replaces the site footer, for instance, it should look exactly the same before and after. If it's giving you any trouble and you're not sure why, ask to get a second pair of eyes on it.

Commit again once you've got it working.

Step 3: Refactor all pages to use custom element

Add the custom element to every page it belongs in. It might make sense to use your editor's Find And Replace tool.

Double-check that everything looks okay, then commit, push, and open a PR.

Clone this wiki locally