Use Custom Elements for Reusable Components! (ES6)

Gina Lee
2 min readAug 7, 2020

Take the example of having multiple cards, that all contain the same “X” close button present on the top right corner.

Here’s what the HTML looks like without using a custom element:

There is a saying — a PRINCIPLE — that goes along the lines of keeping yourself dry. What is dry, you might ask? Don’t Repeat Yourself. If there’s a way to remove duplication, do it! Your code will be shorter and look much cleaner!

And now, to present the same layout, using a custom element <close-btn>:

Isn’t that way nicer to look at? 😆

In the next section, I will go into how a custom element is created using Javascript ES6.

Ok, I know what you might be thinking. “Is this really much better? It’s longer than just repeating the close button HTML code 3 times!

Let me tell you why it’s better. First of all, you get a clean HTML file. Second, although you have close button components that look and function the same way, they are not the same component. Each close button component is its own entity living in different places on the DOM. Therefore, creating a custom element is helpful because it lets you encapsulate all things close button related in one place, meanwhile referencing the particular custom element instance.

Now that that’s settled, how does this work?

Using ES6’s class syntax, you create a class object that extends the HTMLElement interface. Then, you would put the created shadow root, its internal shadow DOM structure, functionality, and CSS within the constructor.

After defining the class, you must register the custom element in order to use it. This is by using the customElements.define() method from the CustomElementRegistry interface.

With that, you simply import this Javascript file into your HTML and behold! You can now use your new CUSTOM built element, <close-btn>! 🎊

--

--