0 day streak
javascript / intermediate
Snippet

Recursive Components with svelte:self

The '<svelte:self>' tag allows a component to include itself recursively. This is essential for rendering nested data structures like tree views, file systems, or recursive menus.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
export let folder;
</script>
<ul>
<li>{folder.name}</li>
{#if folder.files}
{#each folder.files as file}
<li>
<svelte:self folder={file} />
</li>
{/each}
{/if}
</ul>
svelte
Breakdown
1
<svelte:self folder={file} />
Instructs the component to render another instance of itself with new props.
2
{#if folder.files}
Provides a base case to ensure the recursion terminates when no more files exist.