How can I pass parameters to on:click in Svelte?
Asked Answered
R

9

116

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{}?


I found the proper way to do it (see comments). Calling the function from an inline handler works.

<button on:click={() => handleClick("parameter1")}>
    It works...
</button>
Rora answered 7/10, 2019 at 0:46 Comment(4)
Thats what even the docs have not explicitly mentioned. But yes thats the way for now i think.. Until they come up with a different solution..Barbican
This isn't a hack, it's how it works. It's explicitly mentioned in the tutorial svelte.dev/tutorial/inline-handlersHat
Thanks for your comments! This "hacky way" of doing it is not so bad after all, but I would dare say that the docs and tutorial are not very explicit about this. Maybe it's just me, though.Submaxillary
For what it's worth, the reason on:click{() => clickHandler(param)} is, as Rich said above, "how it works", is because one needs to pass a reference to the function needing to be executed. By calling on:click{clickHandler(param)}, you are executing the function immediately. That's not what you want.Indecisive
M
117

TL;DR

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


You have to use a function declaration and then call the handler with arguments. The arrow function is elegant and is 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 a 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 a comment: This is not a hack, but it is what the documentation shows also in their tutorials: Events/Inline handlers

Meisel answered 4/4, 2020 at 8:2 Comment(3)
for me it is not work <button on:click={handleClick("arg1")}> only <button on:click={() => handleClick("arg1")}>Abreu
on:click={() => handleClick("arg1", "arg2")} is the way to goThrasher
At a philosophical level, I guess having it this way also makes it as close to vanilla JavaScript as possible. The idea of "when in doubt, do it like JavaScript" holds here (and of course they've done some work behind the hood to make it efficient). In fact, if I hadn't bothered looking it up I'd probably have intuitively gone for this solution anyway :PToper
A
36

Rich has answered this in a comment, so credit to him, but the way to bind parameters in a click handler is as follows:

<a href="#" on:click|preventDefault={() => onDelete(projectId)}>delete</a>
<script>
    function onDelete (id) {
      ...
    }
</script>

To provide some extra detail for people who also struggle with this, and it should be in the docs if it isn't, you can also get the click event in such a handler:

<a href="#" on:click={event => onDelete(event)}>delete</a>
<script>
    function onDelete (event) {
      // If it's a custom event you can get the properties passed to it:
      const customEventData = event.detail

      // If you want the element, you guessed it:
      const targetElement = event.target
      ...
}
</script>

Svelte documentation/tutorial: inline handlers

Arduous answered 2/11, 2019 at 18:17 Comment(3)
Why are you using links for buttons, when they have no URL?Looming
Because I build PWAs which have links as fallbacks, so it's more a reason of habit. It could easily be a button.Arduous
I think a button will submit the form on the page even if its outside the form. At least that was what I was seeing even with <button type="button">...</button>Bushwhacker
N
6

There isn't any clear way mentioned in the documentation and your solution will work, but it is indeed not very elegant. My own preferred solution is to use currying in the script block itself.

const handleClick = (parameter) => () => {
   // Actual function
}

And in the HTML:

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

Beware of currying

As mentioned in the comments, currying has its pitfalls. The most common one that in the above example handleClick('parameter1') will not be fired when clicking, but rather on rendering, returning a function that in turn will be fired onclick. This means that this function will always use 'parameter1' as its argument.

Therefore using this method would only be safe if the used parameter is a constant of some kind and will not change once it's rendered.

This would bring me to another point:

  1. If it's a constant used a parameter, you could as well use a separate function

    const handleParameter1Click = () => handleClick('parameter1');
    
  2. If the value is dynamic but available within the component, this could still be handled with a stand-alone function:

    let parameter1;
    const handleParameter1Click = () => handleClick(parameter1);
    
  3. If the value is dynamic, but not available from the component, because this is dependent on some kind of scope (e.g., a list of items rendered in a #each block) the 'hacky' approach will work better. However, I think it would be better to in that case have the list-elements as a component themselves and fall back to case #2

To conclude: currying will work under certain circumstance, but it is not recommended unless you are very well aware and careful about how to use it.

Niple answered 7/10, 2019 at 5:35 Comment(5)
Don't do this! Just create an inline function (on:click={() => handleClick('parameter1')})Hat
Just realised that's the proposal you were responding to. The reason I advise against the currying approach is twofold — first, it's less immediately clear what's happening (people tend to assume that handleClick('parameter1') is what happens when the click happens, incorrectly. Secondly, it means that the handler needs to be rebound whenever parameters change, which is suboptimal. Currently, there's a bug, meaning that doesn't work anyway svelte.dev/repl/a6c78d8de3e2461c9a44cf15b37b4dda?version=3.12.1Hat
True, I was not aware of that bug never encountered it myself. Then again in the codebase I am working on we never pass parameter like this, they are almost always objects and that seems to work: svelte.dev/repl/72dbe1ebd8874cf8acab86779455fa17?version=3.12.1Niple
I updated my answer with some currying pitfalls and other reflections. Thanks for the inputNiple
Ah yep, it'll work with objects, as long as the reference itself doesn't change (and the underlying bug will get fixed in due course as well)Hat
S
3

A Pug solution

Assign with !=. Yes, assign with !=. It is weird as hell. Example: Foo(on:click!='{() => click(i)}'). This is per documentation for svelte-preprocess (a necessary transpiler to include templates in Pug):

Pug encodes everything inside an element attribute to html entities, so attr="{foo && bar}" becomes attr="foo &amp;&amp; bar". To prevent this from happening, instead of using the = operator use != which won't encode your attribute value [...] This is also necessary to pass callbacks.

Personally, I will use a utility function for this, because assigning with != bothers me too much.

// Utility function
const will = (f, v) => () => f(v);
// In a Pug template, we can again assign with =
Foo(on:click='{will(click, i)}')
Somnambulation answered 15/9, 2021 at 8:16 Comment(1)
I was losing my mind. Thanks very much for this Pug solution...Unmoving
B
2

I got it working with this:

<a href="#" on:click|preventDefault={onDelete.bind(this, project_id)}>delete</a>
function onDelete(id) {
}
Bushwhacker answered 1/11, 2019 at 17:26 Comment(0)
B
0

Here it is with a debounce method and event argument:

<input type="text" on:keydown={event => onKeyDown(event)} />
const onKeyDown = debounce(handleInput, 250);

async function handleInput(event){
    console.log(event);
}
Bushwhacker answered 6/12, 2019 at 22:8 Comment(0)
D
-1

Check out sortable-table.

Note the passing of parameters to the header click handling function in a magical way. I don't have any idea why this is so. Auto-currying maybe?

Distrust answered 24/3, 2021 at 6:49 Comment(1)
the sort function in that REPL returns a function, and that function handles the click. when the component is loaded, sort is called twice, with the name of the column, and returns two functions, one which will sort by id, and one which will sort by val.Arduous
S
-1

I'm using:

{#each data as item}
   <li on:click={handle(item)}>{item.name}</li>
{/each}

...and it is not running the function when it renders; it works on click.

Sabatier answered 24/8, 2021 at 22:25 Comment(4)
If you can prove this works for you in the REPL I would be shocked. Here's a REPL showing that the functions will indeed run on initial render and not on click at all. svelte.dev/repl/741340eb0ec34ae89601a1f069747c22?version=3.44.1Elberfeld
You are right, I dont remember why I wrote that it worked back then.Sabatier
Happens to me all the time, things stop working or change completely so often.Elberfeld
I've actually seen this work before too, and I dont know why.Carrizales
K
-1

It appears to work in this particular situation. I don't know enough to understand why, but I thought it was relevant since even Rich says it shouldn't. I couldn't find any reason after searching that made this case unique.

REPL

Kunming answered 18/8, 2022 at 7:51 Comment(2)
What appears to work in this particular situation? Which of Rich's comments is referred to? He has made a lot comments.Pedo
OK, the OP may have left the building: "Last seen more than a month ago"Pedo

© 2022 - 2024 — McMap. All rights reserved.