How to Properly Pass Params to on:click in Svelte

Ferenc Almasi β€’ 2022 October 28 β€’ πŸ“– 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:

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

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.

Looking to improve your skills? Learn how to build reactive apps with Svelte + Tailwind.
Master Svelte

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:

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

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

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:

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

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 Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended