Tech News
← Back to articles

Building optimistic UI in Rails (and learn custom elements)

read original related products more articles

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 and are custom elements. They are just HTML tags with JavaScript behavior attached.

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 in your HTML and it will display the message. The connectedCallback runs when the element is added to the page. This is similar to Stimulus’s connect() method. There is also, just like with Stimulus, a disconnectedCallback . This can be used similar to Stimulus’: removing event listeners and so on.

Custom element names must contain a hyphen. This prevents conflicts with future HTML elements. So works, but does not.

Attributes and properties

... continue reading