javascript / intermediate
Snippet
Tree Structures with Recursive Components
The <svelte:self> element allows a component to include itself recursively. This pattern is ideal for rendering hierarchical data like file systems or nested comments.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- Folder.svelte --><script>export let name;export let children = [];</script><ul><li>{name}</li>{#if children.length > 0}<ul>{#each children as child}<svelte:self {...child} />{/each}</ul>{/if}</ul>
svelte
Breakdown
1
<svelte:self {...child} />
Renders the current component again for each child in the array.
2
{#if children.length > 0}
A base case check to prevent infinite recursion.