Web Components

The Web Components API can allow you to reuse code and develop a personal style with ease. Let's learn about them in this lesson.

Introduction

Here’s the official definition of Web Components:

“Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.”
MDN.

In English, that just means that Web Components are a way for you to create your own HTML tags that you can reuse later.

Front-end frameworks like React or Vue have their own set of components (buttons and such) with all the JavaScript functionality and styling included. Web Components work a lot like those components. You can actually easily integrate Web Components with something like React.

There are three primary ways that Web Components can be created. They can be used individually, but generally, they are all used together to create a web component.

Custom elements

Custom elements give us the capability to create our own tags. A custom element can be created by adding a class to the page’s JavaScript.

Let’s look at the two different kinds of custom elements.

Autonomous custom elements

Autonomous custom elements can be used to create an entirely new tag from scratch.

In the code example below, for instance, we’re creating a new element or tag called <lesson-section>. Let’s take a look at each file.

JavaScript

  • Line 1: Declaring a class called Lesson that is built upon the HTMLElement class.
  • Line 2: Declaring a definition for the constructor. The constructor is usually used to instantiate any state and event listeners. It’s always called whenever an instance of the element (or class) is created or upgraded.
  • Line 3: Calling the constructor of the HTMLElement class, super();
  • Line 4: Setting the inner HTML of the tag. It’s enclosed in <h3> tags, so any global styling via the CSS style sheet on <h3> would be applied to the inner HTML. this.getAttribute('heading') ‘gets’ us the value of the heading attribute passed to the tag.
  • Line 8: This line is used to define the custom element. The following function is used to do so: window.customElements.define(<tag-name>, <ClassName>);. Note that the tag name must have a hyphen.

HTML

Lines 5-7 are of interest. The tag <lesson-section> is instantiated with the heading attribute passed in. This is much like the href attribute getting passed into the hyper link <a> tag.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.