Svelte 26 🧡 Passing Snippets as Explicit Component Props
Svelte 5’s transition from the rigid, implicit <slot /> system to the flexible, explicit snippet system marks a major evolution in how we compose components. By treating UI fragments as data that can be passed as component props, we gain the ability to create highly generic wrapper components that don’t need to know the implementation details of the content they render. This pattern moves UI composition away from “slotting into holes” and toward standard functional dependency injection.
Passing snippets as props allows developers to define the “shell” of a component—such as a Card, Modal, or Data Table—while leaving the “content” to be defined by the parent. Because these snippets are passed via the $props() rune, they are subjected to the same type-checking and interface enforcement as any other piece of data, leading to a much more predictable and robust developer experience. This chapter details the syntax and architectural patterns required to implement this compositional model effectively.
Key point: Passing snippets as props transforms UI composition into a type-safe function call; it allows parent components to inject dynamic templates into a child component’s structure, effectively replacing the old, implicit slot-based architecture with explicit prop-based injection.
Why passing snippets as props exists
The explicit contract problem. Legacy slots were “magic holes” in a component. You never knew for sure what the parent was going to put inside. Passing snippets as props creates an explicit contract where the child defines exactly which parts of its UI are customizable.
Type-safe composition. Since snippets are passed as props, we can annotate them with the Snippet type. This enables TypeScript to verify that the passed UI logic matches the child’s expectations, catching bugs before they reach the browser.
The “Inversion of Control” pattern. By passing snippets as props, you invert the control of component composition. The child component provides the layout container, but the parent provides the specific visual logic, leading to highly reusable, agnostic containers.
Namespace and collision avoidance. Legacy named slots could easily lead to name collisions in deep component trees. Snippet props are localized to the component instance, making it impossible for parent-child components to accidentally overwrite each other’s content.
The dynamic render requirement. Because snippets are just values, you can store them in arrays, pass them through multiple layers of components (prop-drilling), or conditionally render them based on application state—things that were historically very difficult to achieve with standard slots.
a. Defining the Snippet type
To pass a snippet, you must use the Snippet type provided by the svelte package. This type acts as a wrapper around the render function. When you define a prop as a Snippet, you are informing Svelte that the parent is expected to provide a renderable template fragment.
import type { Snippet } from 'svelte';
let { header, content }: { header: Snippet, content: Snippet } = $props();
If your snippet needs to accept data (like an array item), you use the generic Snippet<[T]> syntax. This allows the child component to provide data to the snippet, ensuring that the parent knows exactly what the snippet will receive when it is rendered. This is the foundation of powerful, data-driven UI composition.
b. Declaring snippet props in components
Snippet props are declared within the $props() rune, just like strings or numbers. This centralization makes it incredibly easy to see the full “API surface” of a component. You don’t need to hunt for <slot /> tags inside the markup; you simply look at the prop interface at the top of the component file.
<script lang="ts">
import type { Snippet } from 'svelte';
let { title, children }: { title: string, children: Snippet } = $props();
</script>
<section>
<h2>{title}</h2>
<!-- Render the snippet using the @render tag -->
{@render children()}
</section>
This pattern allows the child to wrap the snippet in its own CSS, padding, or container logic. The parent provides the content, and the child provides the structural envelope. This separation of concerns is the hallmark of professional, scalable component architectures.
c. Rendering snippets via @render
Once a snippet is passed as a prop, it is rendered using the {@render ...} directive. If the snippet requires arguments, you pass them inside the parentheses, exactly as you would with a standard function call. This syntax is robust and allows for complex composition, such as rendering snippets inside loops or conditional blocks.
<!-- Rendering a simple snippet -->
{@render children()}
<!-- Rendering a snippet with arguments -->
{#each items as item}
{@render itemTemplate(item)}
{/each}
Because {@render} is a tag, it is easy to spot in your templates. It serves as an explicit indicator of “here, the component renders a piece of content passed from outside.” This clarity is invaluable when debugging deeply nested component trees, as it clearly signals that the content source is external to the current component.
Complete Example Session
// ============================================
// PART 1: THE WRAPPER COMPONENT
// ============================================
// Card.svelte
import type { Snippet } from 'svelte';
let { title, header, children }: {
title: string,
header: Snippet,
children: Snippet
} = $props();
<div class="card">
<div class="header">{@render header()}</div>
<h2>{title}</h2>
<div class="body">{@render children()}</div>
</div>
// ============================================
// PART 2: THE PARENT USAGE
// ============================================
// App.svelte
{#snippet myHeader()} <Icon /> <span>Info</span> {/snippet}
<Card title="User Profile" header={myHeader}>
<p>User bio details...</p>
</Card>
This session demonstrates how the Card component remains agnostic about its header and body content, delegating that responsibility entirely to the parent via snippets passed as props.
Quick Reference
Types and Syntax
| Type/Syntax | Usage |
|---|---|
Snippet | Basic template fragment |
Snippet<[T]> | Template fragment with one argument T |
{@render name()} | Invoke snippet |
$props() | Capture snippet as prop |
The Composition Contract
| Role | Responsibility |
|---|---|
| Parent | Defines the “what” (Content) |
| Child | Defines the “where” and “how” (Structure/Style) |
Best Practices
✅ Do This:
// Explicitly type your snippets
let { item }: { item: Snippet<[Item]> } = $props(); // ✅
// Always check for existence before rendering
{@render header?.()} // ✅
// Use descriptive prop names (header, body, footer)
let { header, body } = $props(); // ✅
❌ Don’t Do This:
// Don't use <slot /> in Svelte 5
<slot name="header" /> // ❌
// Don't pass snippet as string
let { header }: { header: string } = $props(); // ❌
// Don't ignore the Snippet type
let { content } = $props(); // 'any' is bad practice // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Missing Type | Forgetting to import Snippet | import type { Snippet } |
| Wrong Args | @render ignores required args | Match snippet signature |
| Runtime Error | Rendering null snippet | Use optional chaining ?.() |
| Boilerplate | Passing simple text as snippet | Use string props instead |
Real-World Examples
1. Card component
let { header, body }: { header: Snippet, body: Snippet } = $props();
2. Data Table Row Renderer
let { row }: { row: Snippet<[Item]> } = $props();
3. Modal with custom footer
let { footer }: { footer: Snippet } = $props();
4. Dynamic tab header
let { tab }: { tab: Snippet<[Tab]> } = $props();
5. Complex list item
let { item }: { item: Snippet<[Entry]> } = $props();
6. Layout Sidebar
let { sidebar }: { sidebar: Snippet } = $props();
7. Error boundary
let { fallback }: { fallback: Snippet<[Error]> } = $props();
8. Breadcrumb segment
let { link }: { link: Snippet<[Path]> } = $props();
9. Accordion trigger
let { trigger }: { trigger: Snippet<[boolean]> } = $props();
10. Dashboard widget wrapper
let { widget }: { widget: Snippet } = $props();
Visual
Snippet Prop Flow
┌──────────────────────────────────────┐
│ PARENT │
│ {#snippet header()}...{/snippet} │
│ <Child header={header} /> │
│ │ │
│ ▼ (Pass as prop) │
│ CHILD │
│ let { header } = $props(); │
│ {@render header()} │
└──────────────────────────────────────┘
The Type-Safe Bridge
┌──────────────────────────────────────┐
│ TYPE: Snippet<[User]> │
│ (Ensures child sends User data) │
│ (Ensures parent accepts User data) │
└──────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Prop Type | Snippet |
| Renderer | {@render} |
| Requirement | TypeScript interface |
| Benefit | Explicit composition |
| Evolution | Legacy slots replacement |
Key takeaways:
- Explicit is better than implicit. Snippet props force you to define exactly which parts of a component can be customized, creating better documentation through code.
- Type-safe UI. Use
Snippet<[T]>to define the shape of data flowing into your templates, preventing runtime errors. - Composition over slots. Adopt the snippet-as-prop pattern as the standard way to build reusable UI shells in Svelte 5.
- Render with args. Pass dynamic data to your snippets to allow children to inject contextual information (like list items) into parent-defined templates.
- Handle optionality. Snippets passed as props might be undefined; use optional chaining
header?.()to safely render them.
Remember: Passing snippets as props is the “final form” of component composition in Svelte 5. By treating your UI as a collection of injectable functions rather than structural holes, you gain a level of control, clarity, and safety that was simply not possible with legacy slots. This approach makes your components easier to reason about, safer to test, and significantly more flexible as your design system grows.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!