0
0
Svelteframework~5 mins

Slot basics (default slot) in Svelte

Choose your learning style9 modes available
Introduction

Slots let you put content inside a component from outside. The default slot is the main place where you add this content.

You want to create a reusable card component that can show different content inside.
You build a modal window and want to put any message or buttons inside it.
You make a layout component and want to insert different page content inside.
You want to wrap some content with styling but keep the content flexible.
Syntax
Svelte
<slot></slot>

The <slot> tag marks where the outside content will appear.

If no content is given, the slot can show default content inside <slot> like <slot>Default text</slot>.

Examples
Basic default slot with no fallback content.
Svelte
<slot></slot>
Default slot with fallback text if no content is passed.
Svelte
<slot>Default content here</slot>
Slot inside a wrapper element to style the inserted content.
Svelte
<div class="wrapper">
  <slot></slot>
</div>
Sample Program

The Box component uses a default slot with fallback text. In App.svelte, the first <Box> has custom content, so it shows that. The second <Box> has no content, so it shows the default fallback text.

Svelte
<!-- Box.svelte -->
<div class="box">
  <slot>Default box content</slot>
</div>

<style>
  .box {
    padding: 1rem;
    border: 2px solid #007acc;
    border-radius: 0.5rem;
    background-color: #e0f0ff;
  }
</style>


<!-- App.svelte -->
<script>
  import Box from './Box.svelte';
</script>

<Box>
  <p>This is custom content inside the box.</p>
</Box>

<Box></Box>
OutputSuccess
Important Notes

Slots help keep components flexible and reusable by letting you insert any content.

Default slot content only shows if no content is passed inside the component.

You can style the slot container to control how inserted content looks.

Summary

Slots let you pass content into components from outside.

The default slot is the main place where this content goes.

If no content is given, default slot content shows instead.