Slim slot

How to use slots in Svelte to define components that can be combined together

Slots are a convenient method that allows you to define components that can be grouped together.

The reverse is also true. From your point of view, slots are a convenient way to configure imported components.

This is how they work.

In the component, you can use<slot />(or<slot></slot>) Syntax.

This is anButton.svelteSimply print one<button>HTML tags:

<button><slot /></button>

For React developers, this is basically the same as<button>{props.children}</button>

Any component that imports it can define what will be put into the slot by adding it to the start and end tags of the component:

<script>
import Button from './Button.svelte'
</script>

<Button>Insert this into the slot</Button>

You can define a default value, and use that default value if the slot is not populated:

<button>
  <slot>
    Default text for the button
  </slot>
</button>

There can be multiple slots in a component, and named slots can be used to distinguish one slot from another. A single unnamed slot will be the default slot:

<slot name="before" />
<button>
  <slot />
</button>
<slot name="after" />

The method of use is as follows:

<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 to the DOM:

<p slot="before">Add this before</p>
<button>
  Insert this into the slot
</button>
<p slot="after">Add this after</p>

Download mine for freeSlim Handbook


More subtle tutorials: