How to pass parameters to on:click in Svelte?

SvelteSvelte 3

Svelte Problem Overview


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>

Svelte Solutions


Solution 1 - Svelte

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

Solution 2 - Svelte

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 docs/tutorial: inline handlers

Solution 3 - Svelte

I got it working with this:

<a href="#" on:click|preventDefault={onDelete.bind(this, project_id)}>delete</a>

function onDelete(id) {
}

Solution 4 - Svelte

Pug solution

Assign with !=. Yes, assign with !=. 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 util functions for this, because assign with != bothers me too much.

// util fn
const will = (f, v) => () => f(v);
// in pug template we can again assign with =
Foo(on:click='{will(click, i)}')

Solution 5 - Svelte

There is no clear way mentioned in the documentation and your solution will work but 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 it's 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 seperate function
const handleParameter1Click = () => handleClick('parameter1');
  1. If the value is dynamic but available within the component, this could still be handled with a standalone function:
let parameter1;
const handleParameter1Click = () => handleClick(parameter1);
  1. If the value is dynamic but not available from the component because this is dependent on some kind of scope (eg: 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 is not recommended unless you are very well aware and careful about how to use it.

Solution 6 - Svelte

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);
}

Solution 7 - Svelte

At risk of necroposting, check out https://svelte.dev/repl/08aca4e5d75e4ba7b8b05680f3d3bf7a?version=3.23.1

sortable table. Note the passing of parameters to the header click handling function in a magical way. No idea why this is so. Auto-currying maybe?

Solution 8 - Svelte

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.

Categories

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionF&#233;lix ParadisView Question on Stackoverflow
Solution 1 - SvelteV. SamborView Answer on Stackoverflow
Solution 2 - SvelteAntony JonesView Answer on Stackoverflow
Solution 3 - SveltechovyView Answer on Stackoverflow
Solution 4 - Svelten-smitsView Answer on Stackoverflow
Solution 5 - SvelteStephane VanraesView Answer on Stackoverflow
Solution 6 - SveltechovyView Answer on Stackoverflow
Solution 7 - SvelteemperorzView Answer on Stackoverflow
Solution 8 - SvelteYuzemView Answer on Stackoverflow