How to Use svelte:self for Recursion in Svelte Components
In Svelte, you use
<svelte:self /> inside a component to call itself recursively. This allows you to render nested or tree-like structures by passing data down and conditionally rendering the recursive call.Syntax
The <svelte:self /> tag is a special Svelte syntax that lets a component render itself recursively. You place it inside the component's markup where you want the recursive call to happen.
Key parts:
<svelte:self />: Calls the same component again.- Props can be passed to
<svelte:self />just like any other component. - Use conditional rendering to stop recursion and avoid infinite loops.
svelte
<script> export let data; </script> {#if data} <div>{data.name}</div> {#if data.children} <ul> {#each data.children as child} <li><svelte:self data={child} /></li> {/each} </ul> {/if} {/if}
Example
This example shows a simple recursive tree component that displays nested items. Each item can have children, and the component calls itself to render those children.
svelte
<script> export let node; </script> <div> <strong>{node.name}</strong> {#if node.children && node.children.length > 0} <ul> {#each node.children as child} <li><svelte:self node={child} /></li> {/each} </ul> {/if} </div> <!-- Usage example --> <script> import Tree from './Tree.svelte'; const treeData = { name: 'Root', children: [ { name: 'Child 1' }, { name: 'Child 2', children: [ { name: 'Grandchild 1' }, { name: 'Grandchild 2' } ]} ] }; </script> <Tree node={treeData} />
Output
Root
- Child 1
- Child 2
- Grandchild 1
- Grandchild 2
Common Pitfalls
Common mistakes when using <svelte:self /> for recursion include:
- Not providing a stopping condition, causing infinite recursion and browser crash.
- Forgetting to pass the correct props to the recursive call.
- Rendering without checking if children exist, leading to errors.
Always use {#if} blocks to control recursion depth and ensure data is valid.
svelte
<!-- Wrong: No stopping condition, infinite recursion --> <script> export let node; </script> <div> {node.name} <svelte:self node={node} /> <!-- This calls itself endlessly --> </div> <!-- Right: Check children before recursion --> <script> export let node; </script> <div> {node.name} {#if node.children && node.children.length > 0} {#each node.children as child} <svelte:self node={child} /> {/each} {/if} </div>
Quick Reference
- <svelte:self />: Use inside a component to call itself recursively.
- Pass props like
<svelte:self prop={value} />to send data down. - Use
{#if}to stop recursion and avoid infinite loops. - Ideal for rendering trees, nested menus, or hierarchical data.
Key Takeaways
Use
<svelte:self /> inside a component to render it recursively.Always include a stopping condition with
{#if} to prevent infinite loops.Pass necessary props to
<svelte:self /> to handle nested data correctly.Ideal for displaying tree-like or nested structures in a clean, reusable way.