Svelte, on:click event inside each block triggers on page load

Viewed 2056

The problem is that in svelte on:click triggers on page load for some reason. Can anybody explain to me why it's happening and how to prevent it so it only triggers when you actually check the box. This only happens if on:click is inside each block.

<script>
    function handleClick(number) {
        alert(number)
    }
    let numbers = [1,2,3,4,5,6]
</script>
{#each numbers as number}
    <input type=checkbox on:click={handleClick(number)}>
{/each}

You can look at it here

1 Answers

The value of on:click should be a function. You're invoking a function — it's no different from doing something like this...

<p>{a} + {b} = {sum(a, b)}</p>

...which, as you'd expect, prints the result of calling the sum function.

Instead, do this:

<input type=checkbox on:click={() => handleClick(number)}>
Related