Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Since snippets — like functions — are just values, they can be passed to components as props.
Take this <FilteredList>
component. Its job is to filter the data
that gets passed into it, but it has no opinions about how that data should be rendered — that’s the responsibility of the parent component.
We’ve already got some snippets defined. Begin by passing them into the <FilteredList>
:
App
<FilteredList
data={colors}
field="name"
{header}
{row}
></FilteredList>
Then, on the other side, declare header
and row
as props:
FilteredList
<script>
let { data, field, header, row } = $props();
// ...
</script>
<script lang="ts">
let { data, field, header, row } = $props();
// ...
</script>
Finally, replace the placeholder content with render tags:
FilteredList
<div class="header">
{@render header()}
</div>
<div class="content">
{#each filtered as d}
{@render row(d)}
{/each}
</div>
Never again will you have to memorize the hex code for MistyRose
or PeachPuff
.
previous next
<script>
import FilteredList from './FilteredList.svelte';
import { colors } from './data.js';
</script>
<FilteredList
data={colors}
field="name"
></FilteredList>
{#snippet header()}
<header>
<span class="color"></span>
<span class="name">name</span>
<span class="hex">hex</span>
<span class="rgb">rgb</span>
<span class="hsl">hsl</span>
</header>
{/snippet}
{#snippet row(d)}
<div class="row">
<span class="color" style="background-color: {d.hex}"></span>
<span class="name">{d.name}</span>
<span class="hex">{d.hex}</span>
<span class="rgb">{d.rgb}</span>
<span class="hsl">{d.hsl}</span>
</div>
{/snippet}
<style>
header, .row {
display: grid;
align-items: center;
grid-template-columns: 2em 4fr 3fr;
gap: 1em;