Custom elements are one of those web platform features that sound complicated but turn out to be surprisingly simple. If you have used Hotwire in Rails, you have already used them. Both
This article walks through what custom elements are, how they compare to Stimulus controllers and how to build them yourself! Starting with a simple counter and ending with an optimistic form that updates instantly without waiting for the server. 🤯
The code is available on GitHub.
What are custom elements?
Custom elements let you define your own HTML tags with custom behavior. They fall under the Web Components umbrella, alongside Shadow DOM (encapsulated styling and markup) and templates (reusable HTML fragments), though each can be used independently. To use custom elements, just define a class, register it with the browser, and use your new tag anywhere (Shadow DOM or templates not required).
Here is the simplest possible custom element:
class HelloWorld extends HTMLElement { connectedCallback () { this . textContent = " Hello from a custom element 👋 " } } customElements . define ( " hello-world " , HelloWorld )
Now you can use
Custom element names must contain a hyphen. This prevents conflicts with future HTML elements. So
Attributes and properties
... continue reading