How to Properly Pass Params to on:click in Svelte
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>
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:
<button on:click={event => updateUser(event, id)}>Update</button>
<!-- Grabbing input value -->
<input type="text" on:keyup={event => update('name', event.target.value)} />
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>
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! π¨βπ»
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: