0 day streak
javascript / beginner
Snippet

Passing Arguments to Event Handler Functions in Svelte

To supply custom arguments to an event listener function in Svelte, wrap the function invocation inside an inline arrow function. This prevents immediate execution during initial component rendering and invokes the handler with specified arguments only upon click events.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
<script>
let message = "No option selected";
function selectOption(optionName) {
message = `Selected: ${optionName}`;
}
</script>
<button on:click={() => selectOption("A")}>Option A</button>
<button on:click={() => selectOption("B")}>Option B</button>
<p>{message}</p>
svelte
Breakdown
1
let message = "No option selected";
Initializes a reactive string state variable to display the current selection.
2
function selectOption(optionName) {
Defines a custom JavaScript function that accepts a parameter to update state.
3
message = `Selected: ${optionName}`;
Updates the message state using template literal interpolation.
4
<button on:click={() => selectOption("A")}>Option A</button>
Attaches an anonymous arrow function to the click event that passes the string 'A' when clicked.
5
<p>{message}</p>
Outputs the updated selection message to the DOM.