Check For Passed Slot in Svelte

- 1 minute read

Sometimes in Svelte, you’ll need to check from a child component whether a specific slot has been passed by a parent component.

Consider the following Item.svelte component, which contains an id and name slot:

<!-- Item.svelte -->

<slot name="id" />

<slot name="name" />

Let’s imagine that sometimes, the name slot is empty - but when it’s not empty, we want to dynamically add some additional markup.

This is where Svelte’s built-in $$slot object comes in handy:

<!-- Item.svelte -->

<slot name="id" />

{#if $$slots.name}
    <div class="exampleContainer">
        <slot name="name" />
    </div>
{/if}

Now, when a parent component passes a name slot to Item.svelte, the slot will be rendered within a special <div> element.

Link to this section Conclusion

There are many other use cases for the $$slot object, and dynamic markup rendering is just one example.