Hasty Briefsbeta

Building optimistic UI in Rails (and learn custom elements)

7 days ago
  • #javascript
  • #rails
  • #web-components
  • Custom elements allow defining custom HTML tags with JavaScript behavior, similar to Hotwire's <turbo-frame> and <turbo-stream>.
  • Custom elements are part of Web Components, alongside Shadow DOM and templates, but can be used independently.
  • To create a custom element, define a class extending HTMLElement, register it with customElements.define(), and use the new tag in HTML.
  • Lifecycle callbacks like connectedCallback and disconnectedCallback mirror Stimulus's connect and disconnect methods.
  • Custom elements can react to attribute changes using attributeChangedCallback and observedAttributes.
  • The is attribute allows extending built-in elements, though Safari lacks support, making autonomous custom elements preferable.
  • Custom elements differ from Stimulus in lifecycle handling, element selection, state management, and event handling, offering a more vanilla JavaScript approach.
  • A simple counter example demonstrates incrementing a value on click, showcasing custom element basics.
  • An optimistic form example updates the UI instantly on submission, reverting if the server fails, enhancing user experience.
  • Custom elements are reusable, work anywhere in the app, and integrate seamlessly with Rails and Turbo Streams.