Debian Codegraph @

www/src/content/essays/webcomponents-work-great.md

raw symbols SCIP
1 ---
2 title: "Web Components Work Great with htmx"
3 description: "This essay by Alexander Petros explores how Web Components can be integrated seamlessly with htmx, a library that enables dynamic web pages through HTML. It discusses the flexibility of htmx in handling interactive elements like Web Components alongside traditional server-driven approaches, such as multi-page apps. By using the example of an editable carnival ride table, Alexander demonstrates how Web Components simplify functionality without the need for heavy JavaScript frameworks, highlighting their compatibility with htmx's DOM-based lifecycle. Alexander also addresses potential challenges and how htmx manages them efficiently."
4 created: 2024-11-13
5 authors: ["Alexander Petros"]
6 tags: ["guides"]
7 ---
8
9 People interested in htmx often ask us about component libraries.
10 React and other JavaScript frameworks have great ecosystems of pre-built components that can be imported into your
11 project; htmx doesn't really have anything similar.
12
13 The first and most important thing to understand is that htmx doesn't preclude you from using *anything*.
14 Because htmx-based websites are [often multi-page apps](https://unplannedobsolescence.com/blog/less-htmx-is-more/), each
15 page is a blank canvas on which you can import as much or as little JavaScript as you like.
16 If your app is largely hypermedia, but you want an interactive, React-based calendar for one page, just import it on
17 that one page with a script tag.
18
19 We sometimes call this pattern "Islands of Interactivity", it's referenced in our
20 explainers [here](/essays/10-tips-for-SSR-HDA-apps#tip-8-when-necessary-create-islands-of-interactivity), [here](/essays/hypermedia-friendly-scripting#islands),
21 and [here](/essays/you-cant#myth-5-with-htmx-or-mpas-every-user-action-must-happen-on-the-server).
22 Unlike JS frameworks, which are largely incompatible with each other, using islands with htmx won't lock you into any
23 specific paradigm.
24
25 But there's a second way that you can re-use complex frontend functionality with htmx, and
26 it's [Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components)!
27
28 ## Practical Example
29
30 Let's say that you have a table that says what carnival rides everyone is signed up for:
31
32 ```html
33 <table>
34 <tr>
35 <th>Name
36 <th>Carousel
37 <th>Roller Coaster
38 </tr>
39 <tr>
40 <td>Alex
41 <td>Yes
42 <td>No
43 </tr>
44 <tr>
45 <td>Sophia
46 <td>Yes
47 <td>Yes
48 </tr>
49 </table>
50 ```
51
52 Alex is willing to go on the carousel but not the roller coaster, because he is scared; Sophia is not scared of either.
53
54 I built this as a regular HTML
55 table ([closing tags are omitted](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#technical_summary) for
56 clarity):
57
58 ```html
59 <table>
60 <tr><th>Name <th>Carousel <th>Roller Coaster
61 <tr><td>Alex <td>Yes <td>No
62 <tr><td>Sophia <td>Yes <td>Yes
63 </table>
64 ```
65
66 Now imagine we want to make those rows editable.
67 This is a classic situation in which people reach for frameworks, but can we do it with hypermedia?
68 Sure!
69 Here's a naive idea:
70
71 ```html
72 <form hx-put=/carnival>
73 <table>
74 <tr>
75 <th>Name
76 <th>Carousel
77 <th>Roller Coaster
78 </tr>
79 <tr>
80 <td>Alex
81 <td><select name="alex-carousel"> <option selected>Yes <option>No <option> Maybe</select>
82 <td><select name="alex-roller"> <option>Yes <option selected>No <option> Maybe</select>
83 </tr>
84 <tr>
85 <td>Sophia
86 <td><select name="sophia-carousel"> <option selected>Yes <option>No <option> Maybe</select>
87 <td><select name="sophia-roller"> <option selected>Yes <option>No <option> Maybe</select>
88 </tr>
89 </table>
90 <button>Save</button>
91 </form>
92 ```
93
94 <br>
95 That will give us this table:
96
97 ```html
98 <table>
99 <tr>
100 <th>Name
101 <th>Carousel
102 <th>Roller Coaster
103 </tr>
104 <tr>
105 <td>Alex
106 <td><edit-cell name="alex-carousel" value="Yes"></edit-cell>
107 <td><edit-cell name="alex-roller" value="No"></edit-cell>
108 </tr>
109 <tr>
110 <td>Sophia
111 <td><edit-cell name="sophia-carousel" value="Yes"></edit-cell>
112 <td><edit-cell name="sophia-roller" value="Yes"></edit-cell>
113 </tr>
114 </table>
115 <button>Save</button>
116 ```
117
118 That's not too bad!
119 The save button will submit all the data in the table, and the server will respond with a new table that reflects the
120 updated state.
121 We can also use CSS to make the `<select>`s fit our design language.
122 But it's easy to see how this could start to get unwieldy, with more columns, more rows, and more options in each cell,
123 sending all that information each time starts to get costly.
124
125 Let's remove all that redundancy with a web component!
126
127 ```html
128 <form hx-put=/carnival>
129 <table>
130 <tr>
131 <th>Name
132 <th>Carousel
133 <th>Roller Coaster
134 </tr>
135 <tr>
136 <td>Alex
137 <td><edit-cell name="alex-carousel" value="Yes"></edit-cell>
138 <td><edit-cell name="alex-roller" value="No"></edit-cell>
139 </tr>
140 <tr>
141 <td>Sophia
142 <td><edit-cell name="sophia-carousel" value="Yes"></edit-cell>
143 <td><edit-cell name="sophia-roller" value="Yes"></edit-cell>
144 </tr>
145 </table>
146 <button>Save</button>
147 </form>
148 ```
149
150 We still have an entirely declarative [HATEOAS](https://htmx.org/essays/hateoas/) interface, both current state (the
151 `value` attribute) and possible actions on that state (the `<form>` and `<edit-cell>` elements) are efficiently encoded
152 in the hypertext, only now we've expressed the same ideas a lot more concisely.
153 htmx can add or remove rows (or better yet, whole tables) with the `<edit-cell>` web component as if `<edit-cell>` were
154 a built-in HTML element.
155
156 You've probably noticed that I didn't include the implementation details for `<edit-cell>` (although you
157 can, [of course](/essays/right-click-view-source), View Source this page to see them).
158 That's because they don't matter!
159 Whether the web component was written by you, or a teammate, or a library author, it can be used exactly like a built-in
160 HTML element and htmx will handle it just fine.
161
162 ## Don't Web Components have some problems?
163
164 A lot of the problems that JavaScript frameworks have supporting Web Components don't apply to htmx.
165
166 Web Components [have DOM-based lifecycles](https://dev.to/ryansolid/web-components-are-not-the-future-48bh), so they are
167 difficult for JavaScript frameworks, which often manipulate elements outside of the DOM, to work with.
168 Frameworks have to account for some [bizarre and arguably buggy](https://x.com/Rich_Harris/status/1841467510194843982)
169 APIs that behave differently for native DOM elements than they do for custom ones.
170 Here at htmx, we agree with [SvelteJS creator Rich Harris](https://x.com/Rich_Harris/status/1839484645194277111): "web
171 components are [not] useful primitives on which to build web frameworks."
172
173 The good news is that htmx [is not really a JavaScript web framework](/essays/is-htmx-another-javascript-framework).
174 The DOM-based lifecycles of custom elements work great in htmx, because everything in htmx has a DOM-based lifecycle, we
175 get stuff from the server, and we add it to the DOM.
176 The default htmx swap style is to just set [
177 `.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), and that works great for the vast
178 majority of users.
179
180 That's not to say that htmx doesn't have to accommodate weird Web Component edge cases.
181 Our community member and resident WC expert [Katrina Scialdone](https://unmodernweb.com/)
182 merged [Shadow DOM support for htmx 2.0](https://github.com/bigskysoftware/htmx/pull/2075), which lets htmx process the
183 implementation details of a Web Component,
184 and supporting that
185 is [occasionally](https://github.com/bigskysoftware/htmx/pull/2846) [frustrating](https://github.com/bigskysoftware/htmx/pull/2866).
186 But being able to work with both the [Shadow DOM](/docs#web-components) and
187 the ["Light DOM"](https://meyerweb.com/eric/thoughts/2023/11/01/blinded-by-the-light-dom/) is a nice feature for htmx,
188 and it carries a relatively minimal support burden because htmx just isn't doing all that much.
189
190 ## Bringing Behavior Back to the HTML
191
192 A couple of years ago, W3C Contributor (and Web Component proponent, I think) Lea Verou wrote the following, in a blog
193 post
194 about ["The failed promise of Web Components"](https://lea.verou.me/blog/2020/09/the-failed-promise-of-web-components/):
195
196 > the main problem is that HTML is not treated with the appropriate respect in the design of these components. They are
197 > not designed as closely as possible to standard HTML elements, but expect JS to be written for them to do anything.
198 > HTML
199 > is simply treated as a shorthand, or worse, as merely a marker to indicate where the element goes in the DOM, with all
200 > parameters passed in via JS.
201
202 Lea is identifying an issue that, from the perspective of 2020, would have seemed impossible to solve: the cutting-edge
203 web developers targeted by Web Components were not writing HTML, they were writing JSX, usually with React (or Vue, or
204 what have you).
205 The idea that [behavior belongs in the HTML](https://unplannedobsolescence.com/blog/behavior-belongs-in-html/) was, in
206 the zeitgeist, considered [a violation of separation of concerns](https://htmx.org/essays/locality-of-behaviour/);
207 disrespecting HTML was best practice.
208
209 The relatively recent success of htmx, itself now a participant in the zeitgeist, offers an alternative path: take HTML
210 seriously again.
211 If your website is one whose functionality can be primarily described
212 with [large-grain hypermedia transfers](/essays/when-to-use-hypermedia) (we believe most of them can), then the value of
213 being able to express more complex patterns through hypermedia increases dramatically.
214 As more developers use htmx (and multi-page architectures generally) to structure their websites,
215 perhaps the demand for Web Components will increase along with it.
216
217 Do Web Components "just work" everywhere? Maybe, maybe not. But they do work here.
218
219 <script>
220 class EditCell extends HTMLElement {
221 connectedCallback() {
222 this.value = this.getAttribute("value")
223 this.name = this.getAttribute("name")
224
225 this.innerHTML = `
226 <select>
227 <option ${this.value === 'Yes' ? 'selected' : ''}>Yes
228 <option ${this.value === 'No' ? 'selected' : ''}>No
229 <option ${this.value === 'Maybe' ? 'selected' : ''}>Maybe
230 </select>
231 `
232 }
233 }
234
235 customElements.define('edit-cell', EditCell)
236 </script>