Getting Started With Web Components Using Stencil
Web components (or Custom Elements) are a set of standardized APIs that allow you to create reusable and encapsulated components for the web. Custom elements allow you to define your own HTML elements and their behavior using JavaScript. This means you can create your own custom elements like <my-element> and define their behavior using JavaScript.
It has been around for quite some time now, but it hasn’t gained notable traction in the frontend world as most are still quite unfamiliar with it, although it’s being widely used in top websites such as YouTube, GitHub, and many more.
There are many benefits to using Web Components, such as:
- Send minimal JavaScript over the wire — As it uses standard Web APIs, you don’t have to send bigger JS bundles over the wire which exceed your application bundle size, as you do with React/Angular.
<script>
const template = document.createElement(“template”);
template.innerHTML = `
<style>
* {
font-size: 200%;
}
span {
width: 4rem;
display: inline-block;
text-align: center;
}
button {
width: 4rem;
height: 4rem;
border: none;
border-radius: 10px;
background-color: seagreen;
color: white;
}
</style>
<button id=”dec”>-</button>
<span id=”count”></span>
<button id=”inc”>+</button>`;
class MyCounter extends HTMLElement {
constructor() {
super();
this.count = 0;
// attaches Shadow DOM in “open” open
this.attachShadow({ mode: “open” });
}
connectedCallback() {
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.getElementById(“inc”).onclick = () => this.inc();
this.shadowRoot.getElementById(“dec”).onclick = () => this.dec();
this.update(this.count);
}
inc() {
this.update(++this.count);
}
dec() {
this.update(–this.count);
}
update(count) {
this.shadowRoot.getElementById(“count”).innerHTML = count;
}
}
customElements.define(“my-counter”, MyCounter);
</script>
<my-counter></my-counter>