Web Components How-To Basics
Written 3 weeks ago
Let’s say we want a web component that says “Hello, World!”
A web component is a custom reusable html tag.
Here’s how we define it
class SayHello extends HTMLElement {
connectedCallback() {
this.textContent = "Hello, World"
}
}
customElements.define("say-hello", SayHello)
The name (like "say-hello"
) must always contain a "-"
so it does not clash with builtin tags.
And here’s how we use it
<say-hello></say-hello>
<script type="module" src="./say-hello.js"></script>
That’s all!
Bonus
You can even style the tag directly by its name:
say-hello {
color: red;
}
Resources