Reputation: 1292
I am building a sidebar component that updates the active link when clicking on one of the sidebar items. Therefore, I need to pass down the current sidebar item object to enable its active state.
Question: how do I pass values to a callback after an on:click event? Here is how I do it on regular javascript:
<script>
const items = [
{
text: "Home",
url: "/"
},
{
text: "Workarea",
url: "/workarea"
},
{
text: "Notes",
url: "/notes"
},
{
text: "Conf",
url: "/conf"
}
];
function click(obj,e) {
e.preventDefault()
var activeItem = obj.id
}
</script>
//HTML
<div class="card" style="width: 18rem;">
<ul class="list-group list-group-flush">
{#each items as item}
<li class="list-group-item">
<a
on:click={onItemClick}
href={item.url}
>{item.text}</a>
</li>
{/each}
</ul>
</div>
I have checked the API and tried to use the bind:xxxx
directives without success.
I expect the code to be able to update the current active sidebar item after clicking on it.
Upvotes: 2
Views: 2421
Reputation: 29615
You need to pass the item
to your handler:
<div class="card" style="width: 18rem;">
<ul class="list-group list-group-flush">
{#each items as item}
<li class="list-group-item">
<a
on:click={() => onItemClick(item)}
href={item.url}
>{item.text}</a>
</li>
{/each}
</ul>
</div>
Upvotes: 4