Svelte Recursive Component events

Viewed 33

So I currently have a svelte tree view in which the data for the parent component is being fetched from API at first, and then any other child element is pulled from the parent's id.

parent.svelte

const let projects = [] \\ being fetch through API
{#each project as project}
    <TreeView children={project}>
{/each}

TreeView.svelte

export let children = '';
{#if expanded}
    {#await pull_all_children(project.id)}
        <p>Loading</p>
    {:then children}
        {#each children as child}
            <svelte:self children={child}/>
        {/each}
    {/await}
{/if}

The tree view looks good so far, and im getting the tree, but I want to be able to click on a child and return to the root.

So something like this root->child1->child3, can anyone guide me on what steps I should take to achieve this? Also, if you see some fix on my logic above, im all ears.

1 Answers

Assuming you have a button somewhere in the child, you could fire a custom event from it:

<script>
  import { createEventDispatcher } from 'svelte';
  const dispatch = createEventDispatcher();
  
  function handleClick() {
    dispatch('activate', {
      // any data you want to pass, maybe an id ?
    });
  }
 </script>

<button on:click={handleClick}>Click here</button>

Then you can listen to this event with on:activate in the root:

<Treeview children={project} on:activate={doSomething} />

Finally, to keep passing it 'upwards' you can use the concept that an event handler without handler is passed on to the parent, so in Treeview you would get this:

<svelte:self children={child} on:activate />

As a final note, the data passed in from the beginning is available on ev.detail in your final handler

function doSomething(ev) {
  const id = ev.detail.id; // if you passed an id
}
Related