Jacques Amsel
Jacques Amsel

Reputation: 1141

How to pass the item from an each loop into a function

I have a component which contains:

{#each menuItems as item}
<div  class="menu-item {item.selected ? 'selected' : ''}" on:click={select(item)}>
    ...stuff...
</div>
{/each}

menuItems is an array of objects:

$: menuItem = [{
id: 'abc',
selected: true,
}]

I have a function called select which needs to take the item from the each loop as a parameter. How would I do this? The current example does not work due to on:click requiring a function like on:click={submit}. I have tried within quotation marks, and that did not work either.

Upvotes: 3

Views: 806

Answers (1)

Tholle
Tholle

Reputation: 112787

By writing on:click={select(item)} you are invoking the select function directly on render. You want to give on:click a function reference, and you could do that by creating a new inline function for every item in the loop.

Example (REPL)

<script>
  const menuItems = [
    {
      id: 'abc',
      selected: true
    },
    {
      id: 'def',
      selected: false
    }
  ];

  function select(item) {
    alert(item.id);
  }
</script>

{#each menuItems as item}
  <div
    class="menu-item {item.selected ? 'selected' : ''}"
    on:click={() => select(item)}
  >
    {item.id}
  </div>
{/each}

Upvotes: 4

Related Questions