Understanding web components — Custom Elements — Part 2

Harsh Vardhan Gautam
3 min readJul 8, 2023

--

Welcome back! I hope you found Part 1 of this series on web components informative and helpful. In Part 2, we’ll be taking things to the next level by diving into the nitty-gritty of creating a web component from scratch. I know that creating web components can seem intimidating, but trust me — with a little bit of guidance and some sample code snippets, you’ll be well on your way to building powerful, flexible, and reusable components that can take your web development skills to the next level. So, let’s get started!

Creating a web component involves defining a new class that extends the built-in HTMLElement class or even any particular element e.g. HTMLVideoElement.

Here, we’ll be going forward with the basic HTMLElement class which provides a basic implementation of a custom element, but by extending it, we can add our own custom behavior and properties.

Basic snippet looks like this.

class MyWebComponent extends HTMLElement {
constructor() {
super();

// Create a new element to display some text
const textElement = document.createElement("span");
textElement.textContent = "This is span coming from `MyWebComponent`";

// Create some CSS
let style = document.createElement("style");
style.textContent = `
span {
color: blue;
}
`;

// Add the style element to the DOM
this.appendChild(style);
// Add the text element to the DOM
this.appendChild(textElement);
}
}

To make our web component usable, we must define it in the CustomElementsRegistry like this.

customElements.define("my-web-component", MyWebComponent);

That’s all it takes to create a web component. Isn’t it easy? Now, to use our web component in HTML, use it like this.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Understanding web components - Part 2</title>
<script src="./src/index.js"></script>
<style>
/* See we've defined styling for span element here.
But if you observe, you'll see that this styling is not
getting applied to the span. Instead, it's getting overwritten
by the style that we've defined inside the web-component.
*/
span {
color: red;
}
</style>
</head>
<body>
<div>
<span>This is a normal span element.</span>
</div>
<div>
<my-web-component />
</div>
</body>
</html>

One of the key features of custom web components is their lifecycle, which allows them to perform setup and cleanup tasks as they’re inserted into and removed from the DOM, and to respond dynamically to changes in their attributes or environment. Now, we’ll take a closer look at the lifecycle methods of custom web components.

There are following lifecycle callbacks available:

  1. constructor() : This is the first method that is called when a custom element is created. It’s used to initialize the element’s properties and attach its Shadow DOM.
  2. connectedCallback() : This method is called when the element is inserted into the document, either by directly appending it to the DOM or by using a JavaScript method like appendChild(). It's typically used to perform setup tasks like adding event listeners or fetching data.
  3. disconnectedCallback() : This method is called when the element is removed from the document, either by being deleted or by being moved to a different part of the DOM. It’s typically used to clean up any resources that were allocated in the connectedCallback() method.
  4. attributeChangedCallback(name, oldValue, newValue) : This method is called when one of the element’s attributes is changed, either by direct assignment or by using a JavaScript method like setAttribute(). It's used to update the element's state or behavior in response to the attribute change.

Take a look at below codesandbox to see the complete example in working.

Thank you for taking the time to read this article on custom web components and their lifecycle methods! Learning new things can be a real pain, but you’re a rockstar for sticking with it and investing in your web development skills. I hope this article has helped demystify some of the complexities of web components and given you some practical insights that you can apply to your own projects. And if you’re excited to learn more, stay tuned for the next part of the series where we’ll dive into the Shadow DOM!

Related Content:

--

--