How to Properly Pass Params to on:click in Svelte

Ferenc Almasi β€’ 2022 October 28 β€’ Read time 2 min read
  • twitter
  • facebook

To properly pass function parameters to on:click and other event handlers in Svelte, we need to call the handler from an inline arrow function with the passed parameters. Take a look at what this looks like in practice:

Copied to clipboard!
<button on:click={() => updateUser(id)}>Update</button>
Calling functions with parameters from on:click

While this might not be the recommended way to handle parameters in React due to performance reasons, as Svelte is a compiler, it will handle inline function calls the right way.

How to Access the Event Object From Functions With Params

Simply put, we still have access to the event object inside inline handlers, which means in order to expose it to the callback function, we just need to pass it as one of the parameters. This can be done in the following way:

Copied to clipboard!
<button on:click={event => updateUser(event, id)}>Update</button>

<!-- Grabbing input value -->
<input type="text" on:keyup={event => update('name',} />
Accessing the event object from inline handlers

While this approach is the recommended way by the official documentation, why do we need to wrap the callback function into an arrow function, and not just call it on its own? For example in the following way:

Copied to clipboard!
<!-- ❌ This will not work as expected -->
<button on:click={updateUser(event, id)}>Update</button>
Calling functions directly without a wrapper

The reason this will not work as expected is that you execute the function immediately as the component loads, and not when someone clicks on the button. This is why we need a function declaration first, and execute our handler only as a callback of the define arrow function.

Want to learn more about Svelte? Check out our introductory tutorial below! Thank you for reading through, happy coding! πŸ‘¨β€πŸ’»

Looking into Svelte 3
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro



This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.