1

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.

2
  • What exactly do you mean by "return to the root"? Commented Sep 7, 2022 at 6:02
  • @Corrl Like finding its way back to its original parent. Commented Sep 7, 2022 at 20:44

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked nice and is in the right direction. The thing is when clicking a child im only getting the child id or child name. How can I get every child it went through? I need a way to backtrack from child through all the parents not just get the child.
you would handle the event in the component itself, add the id to the existing 'details' object and raise the event again
Worked like a charm! I had it all but was missing passing the handler through the recursive child call. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.