Web Component authors already know how powerful slots are, but what if you could do even more with them? Here's an interesting technique to use (or ab

Dynamic Slots

submited by
Style Pass
2024-04-29 01:00:03

Web Component authors already know how powerful slots are, but what if you could do even more with them? Here's an interesting technique to use (or abuse) slots in your custom elements. I've been calling the pattern dynamic slots.

If you're wondering why one slot has a name and the other doesn't, that's because there are two types of slots! By default, all content goes into the aptly named default slot — the one without a name attribute.

Elements with a slot attribute, however, will go inside of the corresponding named slot. A named slot is simply a slot with a name attribute. In this case, the <img slot="icon"> will be "slotted" into the named slot <slot name="icon">.

If you're feeling comfortable with everything up to this point, you're ready to move onto the next section. Otherwise, I'd suggest reading more about templates and slots before continuing.

Since slots can be named arbitrarily, we have a lot of flexibility here. And since there's no limit as to how many can exist in a shadow root, we can do some pretty interesting things. Here's another contrived example. This time, we'll build a custom element grid that accepts an [oversimplified] attribute of columns and rows.

Leave a Comment