Sometimes you want a component to show itself inside itself. This helps when you have things like lists inside lists or trees. svelte:self lets a component call itself easily.
0
0
svelte:self for recursive components
Introduction
Showing a folder inside a folder in a file explorer
Displaying comments that have replies, which can have replies too
Drawing a family tree where each person can have children
Making a menu with submenus inside menus
Syntax
Svelte
<script> export let data; </script> {#if data.children} {#each data.children as child} <svelte:self data={child} /> {/each} {/if}
<svelte:self /> means the component calls itself.
You can pass props like normal to <svelte:self />.
Examples
This shows an item name and then calls itself for each child item inside a list.
Svelte
<script> export let item; </script> <p>{item.name}</p> {#if item.children} <ul> {#each item.children as child} <li><svelte:self item={child} /></li> {/each} </ul> {/if}
This displays a comment and then shows all its replies by calling itself recursively.
Svelte
<script> export let comment; </script> <div> <p>{comment.text}</p> {#if comment.replies} <div class="replies"> {#each comment.replies as reply} <svelte:self comment={reply} /> {/each} </div> {/if} </div>
Sample Program
This component shows a tree structure. It prints the node name and calls itself for each child node, adding indentation and a border to show levels.
Svelte
<script> export let node; </script> <div style="margin-left: 1rem; border-left: 1px solid #ccc; padding-left: 0.5rem;"> <p>{node.name}</p> {#if node.children} {#each node.children as child} <svelte:self node={child} /> {/each} {/if} </div>
OutputSuccess
Important Notes
Using svelte:self is simple and avoids extra imports for recursive calls.
Be careful to have a stopping condition (like no children) to avoid infinite loops.
Time complexity depends on the size of the data tree you render.
Summary
svelte:self lets a component call itself inside its own template.
This is useful for showing nested or recursive data like trees or comments.
Always pass the right data and have a base case to stop recursion.