What are Svelte 5 snippets and how do they replace slots?
Answer
Snippets are Svelte 5's replacement for slots, offering more flexibility. They are reusable chunks of template that can be passed to components or used locally. Defining a snippet: {#snippet header(title)} <h1>{title}</h1> {/snippet}. Rendering a snippet: {@render header('My Title')}. Passing snippets to components: snippets defined in a parent's scope can be passed as props: <Table {header} {row} {footer} />. Inside the Table component: let { header, row, footer } = $props(); {@render header()}. Improvements over slots: Parameters: snippets can accept arguments (like render props in React). Portability: snippets can be passed to any component, not just the direct parent. Default snippets: the content between component tags is the default snippet: <Component>This is the default snippet</Component>, accessed as children prop. Conditional rendering: {#if children} {@render children()} {/if}. Snippets make component APIs more explicit and flexible than slots.
More Svelte / SvelteKit Questions
View all →- Advanced How does Svelte 5's reactivity model with $state differ from Svelte 4?
- Advanced What is SvelteKit's data loading waterfall problem and how do you solve it?
- Advanced How do you implement real-time features in SvelteKit?
- Advanced What is the SvelteKit shallow routing feature?
- Advanced How does SvelteKit handle static asset optimization?