0
0
Svelteframework~3 mins

Why Action parameters in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how passing parameters to actions can save you from endless repetitive code!

The Scenario

Imagine you want to add a tooltip to many buttons on your webpage, each showing different text when hovered.

You try to write separate event listeners for each button manually.

The Problem

Manually adding event listeners for each element is repetitive and error-prone.

If you want to change the tooltip behavior, you must update every listener separately.

This wastes time and makes your code messy.

The Solution

Svelte's action parameters let you pass custom data to reusable actions.

This means you write one action for the tooltip and customize it easily for each element.

It keeps your code clean and flexible.

Before vs After
Before
button.addEventListener('mouseenter', () => showTooltip('Save'));
After
<button use:tooltip={"Save"}>Save</button>
What It Enables

It enables writing one flexible action that adapts to different elements by receiving parameters.

Real Life Example

Adding a reusable drag-and-drop action where each draggable item can have different drag data passed as a parameter.

Key Takeaways

Manual event handling for each element is slow and repetitive.

Action parameters let you customize reusable actions easily.

This leads to cleaner, more maintainable code in Svelte apps.