ButterCMS Logo

Using Web Components with ButterCMS

Published on
Updated on
12 min read
GSD

From an architectural point of view, a Component is a reusable part of a codebase that contains both UI and code. This concept is at the base of a lot of modern front-end frameworks like React or Angular. Web Components is a suite of native technologies that let developers create Components without the help of any third-party libraries, to use in their web pages and web apps. In this post, we will cover the APIs that compose the Web Components suite and how to integrate them with ButterCMS.

The APIs

Web Components consist of three main technologies

templates_256x256.png HTML Templates: the <template> tag is useful if you want to keep content that can be used by JavaScript code as a “stamp” to create dynamic content.

custom-elements_256x256.png Custom Elements: this API lets developers create their own fully-featured DOM elements.

undefined Shadow DOM: This technique is useful if the web components should not be affected by the DOM outside the component itself.


Shadow DOM is out of scope for this first post about Web Components. In this article, we will explore the first two APIs with some examples as references. All three APIs are available in modern browsers such as Chrome, Safari and Firefox, and they will soon be available be available soon in Edge. In any case, a polyfill is available on npm.

blog-cta-any-stack_800x100.png

A Basic Web Component

In this first example, we will use the Custom Elements API to create a simple “Hello, world!” Component in order to understand how this API works. To create a Custom Element, we need to create a class that extends HTMLElement, like the one that you see in the followingnext snippet.

export default class HelloWorld extends HTMLElement {
  connectedCallback () {
    this.innerHTML = '<div>Hello World!</div>'
  }					
} 

The connectedCallback method will be invoked when the component is connected to the DOM and ready to work. In this callback, you should put initial rendering and attaching DOM event handlers.

Before using the HelloWorld component, we need to give it a tag name. We can do that via the customElements object.

window.customElements.define('hello-world', HelloWorld)

With the previous instruction, we are linking the HelloWorld class to the hello-world HTML tag. Now it’s possible to use the newly created tag like any other standard HTML element.

<hello-world></hello-world>

Congrats! You just created your first Web Component.

Using HTML Templates

In the next example, we will create a ButterCMSList component that will utilize the JavaScript ButterCMS client to fetch a list of posts and display them in a list. To do that we will need two