How to pass arguments to events like on:click in Svelte

Johnny Simpson - May 11 '22 - - Dev Community

Svelte events are the way we add interactivity to components in Svelte. A common issue with Svelte events is adding arguments to functions called within them. For example, suppose we have a basic counter, which increases any time the user clicks on it:

<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
    const addToCounter = function() {
        ++x;
    }
</script>

<button id="counter" on:click={addToCounter}>{x}</button>
Enter fullscreen mode Exit fullscreen mode

This works fine, but let's say we want to change it so that we increase the counter by a certain amount whenever it is clicked. We might try changing the code to something like this:

<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
    const addToCounter = function(amount) {
        x += amount;
    }
</script>

<button id="counter" on:click={addToCounter(5)}>{x}</button>
Enter fullscreen mode Exit fullscreen mode

But this WONT work - instead we need to change our event to contain a function instead. To add arguments to our addToCounter function, we have to do something like this instead:

<button id="counter" on:click={() => addToCounter(5)}>{x}</button>
Enter fullscreen mode Exit fullscreen mode

Here, we call a function, which returns the value produced by addToCounter. This also works for events, so if you want to pass the event or e object to your function, you could do something like this:

<button id="counter" on:click={(e) => addToCounter(e)}>{x}</button>
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .