Slots in Svelte provide a powerful way to define components that can be easily composed together or configured when imported. In this blog, we will explore how slots work in Svelte and how you can leverage them to create dynamic and reusable components.
Defining Slots
To define a slot in a component, you can use the <slot />
or <slot></slot>
syntax. For example, let’s consider a Button.svelte
component that outputs a <button>
HTML tag:
<button><slot /></button>
For developers familiar with React, this is similar to using <button>{props.children}</button>
.
Using Slots
When importing the Button
component, you can provide the content that will be inserted into the slot by adding it between the opening and closing tags of the component:
<script>
import Button from './Button.svelte';
</script>
<Button>Insert this into the slot</Button>
Default Slot
You can define a default content for the slot, which will be used if no content is provided when using the component:
<button>
<slot>
Default text for the button
</slot>
</button>
Named Slots
Svelte also allows defining multiple slots in a component, and you can distinguish them using named slots. The unnamed slot acts as the default slot:
<slot name="before" />
<button>
<slot />
</button>
<slot name="after" />
To use named slots, you can specify the slot name using the slot
attribute:
<script>
import Button from './Button.svelte';
</script>
<Button>
Insert this into the slot
<p slot="before">Add this before</p>
<p slot="after">Add this after</p>
</Button>
This will render the following DOM structure:
<p slot="before">Add this before</p>
<button>
Insert this into the slot
</button>
<p slot="after">Add this after</p>
By leveraging slots and named slots in Svelte, you can create highly reusable and customizable components, enabling you to easily compose different parts together based on your specific needs.