recursionsvelte

How can I render a component in its own component (recursively) in svelte?


I'm trying to make a recursive component that acts as a sort of tree view, where the component takes in an array.

App.svelte

<script>
    import Tree from "./Tree.svelte"
    let name = 'world';
</script>

<Tree arrayTree={[1, 2, [3, 4], 5, 6, 7, [8, [9, 10]], 11, 12]}/>

Tree.svelte

<script>
    export let arrayTree = []
    export let level = 0
</script>

{#each arrayTree as branch}
    {#if Array.isArray(branch)}
        <!-- How do I do this? -->
    {:else}
        <p>{'-'.repeat(level)}{branch}</p>
    {/if}
{/each}

My goal is to re-render the component inside, but I can't re-call <Tree> inside the component, or else it says: Tree is not defined. Is there any way that I can accomplish this?

Svelte REPL


Solution

  • For Svelte 5, you can import the file from itself and call it normally:

    <script>
        import Tree from "./Tree.svelte"
        export let arrayTree = []
        export let level = 0
    </script>
    
    {#each arrayTree as branch}
        {#if Array.isArray(branch)}
            <Tree arrayTree={branch} level={level + 1}/>
        {:else}
            <p>{'-'.repeat(level)}{branch}</p>
        {/if}
    {/each}
    

    The previously recommended solution, svelte:self, was deprecated in Sept. 2024 because it isn’t needed and didn’t type-check.