Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte removing element not working from list of elements

I want to remove child element from list of elements based on user click, It worked well before adding custom component inside each

{#each list as item}
    <div on:click={(event) => remove(item)}> {item} </div>
{/each}

After adding child component last element removed instead of clicked element

<script>
    import Child from './Child.svelte';

    let name = 'world';
    let list = ["item 1", "item 2", "item 3", "item 4"]
    
    const remove = (item) => {
        console.log(item)
        if(item){
    list = list.filter(t => t !== item);
  }
 }
</script>
{#each list as item}
<div on:click={(event) => remove(item)}> <Child item={item}/> </div>
{/each}

Here I have added my child component.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
 export let item;
    const a = item.slice(0,6)
</script>

<p >{a} </p>

>Solution :

In your child component you are slicing the item after that you are using it in your child component.

export let item;
const a = item.slice(0,6)

Svelte needs to find the index or the same item to remove the selected element

Add index in each it will work.

{#each list as item, index (item)}
<div on:click={(event) => remove(item)}> <Child item={item}/> </div>
{/each}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading