πŸŽ„ Get 50% off from our JavaScript course for the holidays! πŸŽ„

How to Properly Pass Params to on:click in Svelte

Ferenc Almasi β€’ 2022 October 28 β€’ πŸ“– 2 min read

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? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

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
Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

πŸŽ‰ Thank you for subscribing to our newsletter. x