Discover how one simple tag lets your component build itself again and again, handling any depth effortlessly!
Why svelte:self for recursive components? - Purpose & Use Cases
Imagine building a family tree or a nested comment section where each item can have children of the same type. You try to write separate components for each level manually.
Manually creating separate components for each nested level is repetitive, error-prone, and impossible to scale when the depth is unknown or dynamic.
svelte:self lets a component call itself recursively, so you can elegantly handle nested structures without repeating code or creating many components.
if (node.hasChildren) { <ChildComponent node={node.children[0]} /> <ChildComponent node={node.children[1]} /> ... }
{#each node.children as child}
<svelte:self node={child} />
{/each}You can build infinitely nested UI structures with simple, reusable components that call themselves as needed.
Displaying a folder tree where each folder can contain files and other folders, all rendered by the same component recursively.
Manual nesting is repetitive and unscalable.
svelte:self enables clean recursive components.
This simplifies rendering nested data like trees or comments.