javascript / expert
Snippet
Polymorphic UI Composition via Typed Snippet Props
Snippets in Svelte 5 replace the old slot system with a more powerful, function-like mechanism. By passing snippets as props, you can create highly polymorphic components. This expert pattern allows the parent to define UI blocks that the child component renders with specific context (like 'item' in the row snippet). This improves type safety and makes the component's API explicit rather than relying on implicit slot placement.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script lang="ts">import type { Snippet } from 'svelte';let {data,header,row}: {data: any[],header: Snippet,row: Snippet<[any]>} = $props();</script><table><thead>{@render header()}</thead><tbody>{#each data as item}{@render row(item)}{/each}</tbody></table>
svelte
Breakdown
1
row: Snippet<[any]>
Defines a snippet prop that accepts one argument of type 'any'.
2
{@render header()}
The @render tag invokes the snippet function to output its HTML content.
3
{@render row(item)}
Invokes the snippet while passing data down to the template block provided by the parent.