0
0
Svelteframework~5 mins

Action parameters in Svelte

Choose your learning style9 modes available
Introduction

Action parameters let you send extra information to a Svelte action. This helps customize how the action works on an element.

You want to reuse an action but with different settings on different elements.
You need to pass a value like a color or speed to control the action's behavior.
You want to update the action when some data changes in your component.
You want to keep your code clean by separating logic and configuration.
Syntax
Svelte
use:actionName={parameter}

The parameter can be any JavaScript value: string, number, object, etc.

Svelte calls the action's update function automatically when the parameter changes.

Examples
Pass a boolean parameter to enable or disable the highlight action.
Svelte
<div use:highlight={true}></div>
Pass an object with multiple settings to a tooltip action.
Svelte
<button use:tooltip={{ text: 'Click me', position: 'top' }}></button>
Pass a simple true value to focus the input when it appears.
Svelte
<input use:focusOnMount={true}>
Sample Program

This example shows an action called highlight that colors the background of an element. You pass a color as a parameter. When the color changes, the action updates the background color automatically.

Click the button to toggle the color between light blue and light green on the second paragraph.

Svelte
<script>
  let color = 'lightblue';

  // A simple action that changes background color based on parameter
  export function highlight(node, color) {
    node.style.backgroundColor = color || 'yellow';

    return {
      update(newColor) {
        node.style.backgroundColor = newColor || 'yellow';
      },
      destroy() {
        node.style.backgroundColor = null;
      }
    };
  }
</script>

<p use:highlight={'lightblue'}>This paragraph has a light blue background.</p>

<button on:click={() => color = color === 'lightblue' ? 'lightgreen' : 'lightblue'}>
  Toggle Color
</button>

<p use:highlight={color}>This paragraph changes color when you click the button.</p>
OutputSuccess
Important Notes

Always return an update function from your action if you expect the parameter to change.

Remember to clean up in the destroy function to avoid side effects.

Summary

Action parameters let you customize Svelte actions with extra data.

Use use:action={parameter} syntax to pass parameters.

Actions can react to parameter changes with an update method.