Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over slots (children) in svelte 3

Tags:

svelte

I wanted to wrap all slots of my custom component. But I couldn't iterate over the slots. My custom component usage looks like:

<Tab>
    <span slot="header">Tab Header 1</span>
    <span slot="header">Tab Header 2</span>
    <span slot="header">Tab Header 3</span>

    ... maybe other slots that are not "header"
</Tab>

Then inside Tab.svelte:

{#each ?? as slot}
    <a class="tab-item">
        <each-slot />
    </a>
{/each}

Above, I am trying to iterate over the children/slots named "header" and wrap them with an anchor tag. How can I do that?

Edit: I don't want to pass javascript objects like:

<Tab headers={['Header 1', 'Header 2', 'Header 3']}>
like image 244
Leone Avatar asked Jun 28 '19 14:06

Leone


1 Answers

It's not possible to iterate over slots. An easier way to do what you describe is to use the context API to have the tabs and their panels work together.

Here's an example of what I'm talking about — we should probably get round to tidying this up and making it available as an npm package, but hopefully it's a good enough base to build upon in its current state.

like image 176
Rich Harris Avatar answered Sep 22 '22 16:09

Rich Harris