0 day streak
javascript / expert
Snippet

Decoupling UI Logic with Snippets

Snippets allow for a 'headless' component pattern where the parent component handles the structural logic (like iteration) while the consumer provides the specific markup for each item via a reusable template block.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
<script>
let { items, renderItem } = $props();
</script>
<ul>
{#each items as item}
<li>{@render renderItem(item)}</li>
{/each}
</ul>
svelte
Breakdown
1
let { items, renderItem } = $props()
Receives a snippet named renderItem as a prop from the parent.
2
{@render renderItem(item)}
Executes the passed snippet, injecting the local item data into the template.