Svelte Slots: Creating Composable Components
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:
1 | <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:
1 | <script> |
Default Slot
You can define a default content for the slot, which will be used if no content is provided when using the component:
1 | <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:
1 | <slot name="before" /> |
To use named slots, you can specify the slot name using the slot
attribute:
1 | <script> |
This will render the following DOM structure:
1 | <p slot="before">Add this before</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.
tags: [“Svelte”, “Slots”, “Components”, “Composable”]