Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

332
Views
How can I dynamically add and remove Svelte components in an each block?

Consider that I have some array of objects, from which things may be added and removed. For each object, I want a Svelte component rendered.

If an object is removed, I want its corresponding Svelte component to be destroyed. If an object is added, I want a corresponding Svelte component to be created.

So far I have something naive, like this:

<script>
  let someObjects = [];

  const addObject = (obj) => {
    someObjects = [...someObjects, obj];
  }

  const removeObject = (idx) => {
    someObjects.splice(idx, 1);
    someObjects = someObjects;
  }

  // ...

</script>

{#each someObjects as obj}
  <SomeComponent object={obj} />
{/each}

This doesn't quite work. If you remove an object partway through the array, then in fact, from Svelte's perspective, the final element of the array has been removed, and other elements have just been modified.

This means that Svelte components are retained but with changed object parameters, which breaks any internal state and what-have-you.

How can I force an object halfway through the array to be destroyed, and keep the others from changing? Is the solution perhaps related to bind:this?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This can be filed away under "read the docs" (thanks Corrl).

Simply ensure your object has some kind of unique identifier as a field, say id, then use a keyed each block:

{#each someObjects as obj (obj.id)}
  <SomeComponent object={obj} />
{/each}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!