Reputation: 39248
What is the recommended approach for passing an argument to a svelte button click handler?
The use case is a repeating button inside an each list. From what I can tell the documentation only shows examples of how to deal with a single button where you can use a global variable to pass data. This is not as practical if you are stamping out a list of buttons in a grid.
Example:
{#each comments as c}
<div class="comment-block">
<div class="comment"> {c.text} </div>
<!-- How can I pass c.id to the approveComment handler? -->
<button on:click="{approveComment}">Approve</button>
</div>
{/each}
<script>
function approveComment() {
// how can I pass an id to this method
}
</script>
One solution is to move the content of the each
block into another component, and pass in the comment object as a prop, but I am curious if you can bind an input value to the button handler per iteration through the loop.
Upvotes: 1
Views: 1891
Reputation: 90
The function approveComment
has the event as an argument. Change your function declaration to:
function approveComment(event) {
// now you can access event.target where you can store
// the id from your button, e.g.:
const id = event.target.value;
console.log(id);
}
You also need to declare the c.id in the value property of your button:
<button on:click={approveComment} value={c.id}>Approve</button>
Upvotes: 3