Nesting Components With Slots in Svelte

- 2 minutes read

In Svelte, you can use slots to nest components together.

Consider the following Container.svelte component:

<!-- Container.svelte -->
<div class="container">
    <slot />
</div>

<style>
    .container {
        align-items: center;
        display: flex;
        justify-content: center;
    }
</style>

By including Svelte’s native <slot /> element (which can also be represented by <slot></slot>) in our component, we can nest an external component inside that slot.

For example, consider the following Item.svelte component, which inherits Container.svelte:

<!-- Item.svelte -->
<script>
    import Container from './Container.svelte';
</script>

<Container>
    <p>This text will be centered inside the container.</p>
</Container>

The code inside the <Container> element in Item.svelte will be nested within the <slot /> element in Container.svelte.

Link to this section Providing fallbacks for empty slots

If no slot is passed to our Container.svelte component, then an error will be thrown. If we want to handle this error, we can provide a default fallback child of the <slot> element:

<!-- Container.svelte -->
<div class="container">
    <slot>
        <p>This is some default text that will appear if no nested code is provided.</p>
    </slot>
</div>

Link to this section Nesting data within multiple slots

We can also use multiple slots by adding a name attribute to our <slot> elements:

<!-- Container.svelte -->
<div class="container">
    <slot name="title" />
    <slot name="description" />
</div>

In this example, we can access those slots from Item.svelte by specifying a slot attribute on the code we pass to the Container element:

<!-- Item.svelte -->
<Container>
    <p slot="title">Title</p>
    <p slot="description">Description</p>
</Container>

Link to this section Conclusion

The <slot> element in Svelte is very powerful, and there is actually a lot more you can do with it.

This tutorial simply encompasses the more basic component nesting features in Svelte, and I use derivations of most of these snippets regularly.

I hope you found it useful!