How to pass parameters to on:click in Svelte?

Félix Paradis picture Félix Paradis · Oct 7, 2019 · Viewed 13k times · Source

Binding a function to a button is easy and straightforward:

<button on:click={handleClick}>
    Clicks are handled by the handleClick function!
</button>

But I don't see a way to pass parameters (arguments) to the function, when I do this:

<button on:click={handleClick("parameter1")}>
    Oh no!
</button>

The function is called on page load, and never again.

Is it possible at all to pass parameters to function called from on:click{}?


EDIT:

I just found a hacky way to do it. Calling the function from an inline handler works.

<button on:click={() => handleClick("parameter1")}>
    It works...
</button>

Answer

V. Sambor picture V. Sambor · Apr 4, 2020

TL;DR

Just wrap the handler function in another function. For elegancy, use arrow function.


You have to use a function declaration and then call the handler with arguments. Arrow function are elegant and good for this scenario.

WHY do I need another function wrapper?

If you would use just the handler and pass the parameters, how would it look like?

Probably something like this:

<button on:click={handleClick("arg1")}>My awesome button</button>

But remember, handleClick("arg1") this is how you invoke the function instantly, and that is exactly what is happening when you put it this way, it will be called when the execution reaches this line, and not as expected, ON BUTTON CLICK...

Therefore, you need a function declaration, which will be invoked only by the click event and inside it you call your handler with as many arguments as you want.

<button on:click={() => handleClick("arg1", "arg2")}>
    My awesome button
</button>

As @Rich Harris (the author of Svelte) pointed out in the comments above: This is not a hack, but is what the documentation shows also in their tutorials: https://svelte.dev/tutorial/inline-handlers