Simple and Effective Web Components

George Gabriel Luță
Blue Harvest Tech Blog
6 min readSep 24, 2020

Hello, world!

Since you are here, that means you are a skilled wielder of the dark practices of web wizardry. You’re just in time as today we are going to explore an interesting topic in the web almanac: web components.

1. Introduction

We are going to explore a curious use-case for this technology and then we will end up with a short hands-on coding session where we are going to brew our very first web component, using nothing but vanilla web standards. Because that’s what web components are. They represent a specification for creating encapsulated reusable components.

But then you might ask “How is this different from the other JS frameworks?”. You are not wrong since that is usually the aim of all the other frameworks out there.

You probably know already how many JS frameworks get born and die each day, almost as if the frontend stage is infinitely expanding, like the universe. Just as an interesting fact, there is even a cool geeky website that you can follow up to check anytime how many days have passed since the birth of the last JS framework.

And that’s not necessarily a bad idea, right? We all love frameworks and the abstractions that they let us use in order to lay the bricks of any modern website. But sometimes, adding an entire framework to encapsulate a single component might be just a bit too much.

2. Technology

For this specific purpose, the web component standard has come to fruition which is based on some simple but effective concepts that we are going to explore in our quest for the web component know-how. Let’s get into it.

Photo by Halacious on Unsplash

Custom Elements

Simply put, these are full-blown HTML elements that include the whole package: custom tags, behavior as well as the template structure. They represent a standard that is defined in the HTML specification right here.

Shadow DOM

You can think of this as a sandbox (almost like an iframe if you may) inside the main DOM where you have the liberty of controlling any structure, behavior, or style, as it is completely detached from the main page. This provides very nice segregation and modularization. As a feature itself, this is also defined in the standard DOM specification which you can inspect here.

HTML Templates

These are the user-defined templates that are implemented through the usage of the <template> and <slot> elements. They contribute to the genericity and extensibility of the component since they can be reused as the basis of a custom element’s structure. And the cool part? They’re not even rendered until they are called upon.

3. Benefits.

What’s in it for us, right? Now you might think that all of this sounds cool and all, but what’s the actual benefit of employing web components to work for us? Well, like every other framework, language, or tool, it all comes down to picking the right tool for the right job. So let’s explore a use-case for our web components.

Let’s imagine a company that’s starting small, creating digital web products. They invest resources in developing their first product using ReactJS because some tech lead fell in love with it or for an actual reason. Then they grow further, implementing the second product. As their codebase expands, so does their design system. For those of you who might be unfamiliar with the concept of a design system, just note down that this is a single source of truth in terms of all the groups of elements (or a component library) that allow a team to design, develop and maintain a digital product.

Photo by Balázs Kétyi on Unsplash

Everything is nice and fresh until one of the new products is projected to start on VueJS, let’s say because it got an extra star on GitHub over the night. In order to keep the consistency and the look and feel on par with the other products, the VueJS product might need reimplementation of some of the components that already exist in React. Oh, noes! We have contradicted the sacred principle of DRY, and so we are condemned for eternity.

But yes, there is a solution to our problem: the missing piece of the puzzle. Web components give you the power of creating shareable components that transgress React, Vue, Angular, and many more. Suddenly the frameworks become a consumer rather than a definer, which opens up the road towards reusability. Nice!

Within our example, crafting the core components of the company’s design system with web components can ensure that no matter how many tech stacks the new products are going to bring to the table, they will all equally benefit of the core component library, which will ensure consistency and will enable the dev teams to focus the spared time on building the more advanced, specialized components alongside the shared ones. There is however a downside to this from two perspectives.

The first one is that not all the current frameworks have full integration with web components. You can check that compatibility here.

The second perspective is that also not all browsers have implemented this standard as per the date of this article. They are supported by default in Firefox (version 63), Chrome, and Opera, with Safari supporting a partial subset of features and Edge working on onboarding it. But it’s going there!

4. Hands-on

Okay, enough with the completely useful and non-nonsense jibber-jabber about the whys. Let’s check the hows by jumping into some code, shall we?

Writing down a simple, native, vanilla JS web component boils down to three incremental steps.

The first step consists in defining a new element of type template and then describe the structure as well as the styling of the element inside a string template. It might look a little messy, but we are here to get our hands dirty. We will then attach this as the innerHTML of our newly created template.

After creating our structure and styling, we can proceed to define the actual component that we are aiming to build. As you will see, this will wrap over the template and enrich it with the magic of JavaScript.

We will create it as an ES6 class, which is going to extend HTMLElement, giving us access to the implementation of a basic element. Inside its constructor, we need to invoke the parent constructor, so we’re gonna call it by its name: super.

Then we are going to attach a shadow DOM tree to our instance, while also setting the mode to open. The reason for doing it is because it allows us to access the shadowDOM via the shadowRoot, which is actually something that we are going to do immediately after.

So in the last line, we are going to attach the template to our shadowRoot (which is an alias for shadowDOM now). Remember, this is the cool part about this whole deal since this component’s shadowDom is isolated from the DOM outside of the component.

That’s it. The bindings are done. One last thing remains. Registering our new component as a custom HTML tag.

Alright, now the scene is set, it’s time to invite the star of the show to make its debut. The way we consume web components is just as simple as to create them. The last step was the one in which we baptized the component as we are going to reference it inside the document, so let’s use that inside a basic HTML structure.

Alright, everything is orchestrated and in place. Let’s fire up the mighty V8 engine and execute all of this. For your convenience, I have replicated all the code inside a pen. Here’s the result.

Neat! It works!

“Look Ma’, no framework! ”.

5. Conclusion

With that being said, we’ve passed the first milestone. You have just baked your very first web component, that you can take with you anywhere you go, regardless of the frameworks that the path leads you to. But that doesn’t mean that the journey ends here. We just scratched the surface of this story.

There is much more to it, including the usage of slots, creating custom attributes, and events. If you are more interested in learning more about it, I can recommend jumping straight to the source, which you can find here. If you would like to dive deep into this topic, you can also look into the implementations of web components, such as Lit Element or Stencil.

If you liked this article and if you’re interested in finding out more, you can reach out to us at Blue Harvest directly. And if you want to chip in on the adventure of uncovering new technologies and applying them to cool projects, check out our website for vacancies.

Happy coding!

--

--