javascript / beginner
Snippet
Passing Custom Arguments to Svelte Event Handlers
In Svelte, event handlers can receive custom parameters by wrapping the function call inside an anonymous inline arrow function, preventing immediate execution on render.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
<script>let greeting = 'Click a button';function setGreeting(name) {greeting = `Hello, ${name}!`;}</script><button on:click={() => setGreeting('Alice')}>Greet Alice</button><p>{greeting}</p>
svelte
Breakdown
1
function setGreeting(name) {
Defines a function that accepts a dynamic name parameter.
2
<button on:click={() => setGreeting('Alice')}>Greet Alice</button>
Uses an inline arrow function to pass 'Alice' as an argument when the click event fires.