Svelte - Actions



Svelte actions are a useful feature that allows developers to create reusable functions that can be directly applied to HTML elements. Using actions allows you to create Svelte components that are shorter, reusable, and easier to maintain.

What are Svelte Actions?

A Svelte action is a JavaScript function that runs when a DOM element is created. It takes the element as an argument, allowing you to manipulate it or add behaviors. These actions are reusable code snippets that can be applied to elements, enabling you to add custom features like focusing an input, making API calls, or animating elements.

Syntax

You can use the use: directive to apply an action to an HTML element in your Svelte component.

<div use:myAction={someParams}></div>

Adding Parameters

In svelte we can create actions that take parameters, letting you customize how they behave. When an action has parameters, it can return an object with an update method that runs whenever the parameters change.

Syntax

When you apply an action to a DOM element, you can pass parameters directly with the use: directive.

<div use:myAction={{ someParam: value }}></div>

Handling Multiple Parameters

Svelte also allows us to use multiple parameters. For such conditions, it is better to use an object or an array instead of separate arguments. This helps avoid problems with JavaScript's comma operator, which only recognizes the last value.

Syntax

In Svelte you can give multiple parameters to an action in the following way

<div use:myAction={{ arg1: 'value1', arg2: 'value2' }}></div>

Example

The following is an example of creating a custom action in Svelte that changes the text color of an element when it is clicked. This example will demonstrate how to create and use a custom action effectively.

<script>
// Define the changeColor action
function changeColor(node) {
    // Function to change the text color
    function handleClick() {
    const colors = ['red', 'green', 'blue', 'orange', 'purple'];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    node.style.color = randomColor;
    }

    // Add the click event listener
    node.addEventListener('click', handleClick);

    // Cleanup function to remove the event listener
    return {
    destroy() {
        node.removeEventListener('click', handleClick);
    }
    };
}
</script>

<style>
p {
    cursor: pointer;
    font-size: 20px;
    margin: 20px 0;
}
</style>

<!-- Use the changeColor action on the paragraph -->
<p use:changeColor>Click me to change my color!</p>

Output

svelte-actions
Advertisements