If You Find Yourself Adding Slots In Web Components, Think Again.

Updated on

DISCLAIMER: Expressed views on this blog are my own.

I've been looking for a way to pass properties and/or attributes to a slot element through to the target element that replaces the slot, but that isn't supported behavior in the W3c spec. I spent a few days trying to google for a solution heavily, but instead landed on the simplest solution. I use lit (http://www.lit.dev) for creating web components because it is perfect for any use case.

I found one idea to pass attributes and properties here: https://pierrelebrun.me/dynamic-properties-on-slots. I find it complex. I don't like the idea so I didn't bother implementing it.

The solution I figured out was to pass a property into the parent element called childRenderer: (idx, ....) => html`<child .propname=${idx}></child>` and remove the slots. Now I have full control of how to render the children again without slots. The children will render and the properties will be passed in.

Essentially, <parent items=${["bla", "blah"]} .childRenderer={(idx, item) => html`etc etc etc..`}></parent>.

It's a trick I learned during my React days, too bad I didn't remember that until now.

Again, glad to have moved away from web frameworks (no more Svelte!) to my own custom solution which I landed on in less than a day after writing about it. My heuristics are just that good. I can make changes and add files with rollup detecting changes and the changed parts gets compiled. Millisecond builds, live reload, server restarts, typescript, web components and all the flexibility I need. My dev experience is more amazing than it was with Svelte. If you want to build lasting, higher performance, low maintenance web apps then forget the all in one frameworks.

You just read "If You Find Yourself Adding Slots In Web Components, Think Again.". Please share if you liked it!
You can read more recent posts here.