Web Components

by Daniela G. January. 10, 18 0 Comment
Tech tutorials

What are Web Components?

Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. If you are familiar with building components in libraries like React or Angular, Web Components should feel similar. Thanks to them, developers are no longer limited to the existing HTML tags that the browser vendors provide.

To recap, Web Components are a collection of building blocks, consisting of:

  • Custom Elements
  • Shadow DOM
  • HTML Imports
  • HTML Templates

The four parts of Web Components are designed to work together, but you can also use each one individually.

Note: Web Components are not fully supported by all browsers yet. In order to apply them, you will need to use polyfills to fill the gaps in browser coverage. Web Components work properly in our newly released version of Coherent GT.

Custom Elements

Custom Elements give us the capability to create new HTML tags. You can do that by crafting your own elements, enhance existing HTML tags or extend components that other developers have authored.

Before we move on let’s look at the rules on how to name and define your Custom Elements:

  • The name of a custom element must contain at least one hyphen (-). For example, <drop-down> is a valid name for custom element, while <drop_down> is not. This is necessary in order to allow the HTML parser to differentiate between a custom element and a regular HTML element.
  • A custom element cannot be self-closing. For example, <drop-down /> is not a valid syntax for a custom element. It should always be written like this: <drop-down></drop-down>.

Create a custom element

  • Create your own custom element:

One can craft a custom element using the customElements.define() browser API method and a JavaScript class that extends theHTMLElement like so:

You can also use an anonymous class if you do not want a named constructor in a current scope:

Once the custom element is defined, we can use it in a web page:

We can define properties on a custom element. For example, let’s add an attribute called fill to our element:

And the usage in the browser:

Note: this refers to the DOM element itself i.e. the instance of the class. So, in the example above, this refers to the <drop-down>.

You can also define a constructor in the class, just call the super() method to have access to the methods and properties of HTMLElement.

  • Extending a custom element

You can do that by extending its class definition:

  • Extend already created components

Browse the element registry and check out if there are any components that you are interested in. Then go to the README tab and learn how to import and use the chosen element in your project.

A custom element can define special lifecycle callbacks for running code during several interesting times of its existence:

  • constructor(): Called when an instance of the element is created or upgraded. Useful for initializing state, setting up event listeners or creating Shadow DOMs.
  • connectedCallback(): Called every time when the element is inserted into the DOM. Useful for running setup code, such as fetching resources or rendering.
  • disconnectedCallback(): Called every time the element is removed from the DOM. Useful for running clean up code (removing event listeners, etc.).
  • attributeChangedCallback(attributeName, oldValue, newValue): Called when an attribute is added, removed, updated, or replaced. Also called for initial values when an element is created by the parser or upgraded.

Note: Only attributes listed in the observedAttributes property will receive this callback.

  • adoptedCallback(oldDocument, newDocument): Called when the element has been moved into a new document.

Shadow DOM

The main idea behind Shadow DOM is to hide all of the markup and styles of a custom element. Let’s look at the usage of a Shadow DOM in a custom element:

When you use in the browser it will be rendered like so:

If you open the browser’s console and inspect the DOM, you will see our new element under the #shadow-root.

shadow DOM

The Element.attachShadow() method attaches a Shadow DOM tree to the specified element and returns a reference to its shadowRoot.

The mode in .attachShadow method is a string specifying the encapsulation mode for the shadow DOM tree. The value of the mode can be:

  • open: Specifies open encapsulation mode. It means elements of the shadow root are accessible from the outside world using element.shadowRoot.
  • closed: Specifies closed encapsulation mode. This mode denies any access to node(s) of a closed shadow root from the outside world.

HTML Imports

Finally, we can include HTML documents into one another using HTML Imports. The import keyword is assigned to the rel attribute of the link element. You import HTML file using <link> tag in an HTML document like this:

HTML Templates

The HTML <template> element defines how to declare pieces of markup at page load. In other words, the template tag allows you to store some markup on the page, which you can later clone and reuse. You can write HTML and CSS code within <template> tag to define how you want the component to be rendered in the browser.

Live Demo

Now we will show you how a drop down menu can be created with Web Components.

Create new .html file, drop-down.html. Here we will define the template, that holds the markup and the styling for our Web Component:

Note: By default, if an element has shadow DOM, the shadow tree is rendered instead of the element’s children. To allow them to render, you need to add placeholders in your shadow tree. That is why we are using the <slot> tag. More information about this element can be found in the MDN documentation.

Now that we have the template, let’s create the custom element. After the <template> tag add a <script> tag. Here we will declare the class for our element. In this example we will use connectedCallback method to attach a shadow to the template and define the element’s behaviour:

And that is it! Now you can use the <drop-down></drop-down> tag multiple times in your project! So let’s see how it looks:

Web components

Тo explore the example in more detail, can check it out in codepen.

For more interesting information regarding Web compnents follow @CoherentLabs on Twitter or start a discussion in our Forum. Also, give Daniela, the creator of the post, some love by tweeting her @DannaGeorgieva.

Useful resources

Custom Elements specification

Shadow DOM specification

HTML Imports specification

HTML Templates specification

Web Components Specifications

Custom Elements v1: Reusable Web Components

Social Shares

Related Articles

Leave a Comment