What is Action in Svelte: Simple Explanation and Example
action is a function that lets you add custom behavior directly to HTML elements when they are created. It is used to interact with the DOM, like adding event listeners or animations, by attaching the function to an element with the use: directive.How It Works
Think of an action in Svelte like giving a special instruction to an HTML element when it appears on the page. This instruction is a function that runs with the element as its input, allowing you to add extra behavior or effects.
For example, if you want to automatically focus an input box when it shows up, you can write an action that tells the input to focus itself. The action runs once when the element is created, and it can also clean up when the element is removed.
This is similar to giving a helper a note attached to a specific item, so the helper knows exactly what to do with that item without changing the rest of the page.
Example
This example shows an action that automatically focuses an input box when it appears on the page.
<script> // Define the action function function autofocus(node) { node.focus(); return { destroy() { // Cleanup if needed when element is removed } }; } </script> <input use:autofocus placeholder="I am focused on load" />
When to Use
Use actions when you want to add custom behavior to elements that involves direct interaction with the DOM. This includes things like:
- Setting focus on inputs
- Adding event listeners that are not covered by Svelte's built-in events
- Integrating third-party libraries that need DOM access
- Adding animations or drag-and-drop functionality
Actions are perfect when you want reusable, clean ways to enhance elements without cluttering your component logic.
Key Points
- An
actionis a function that runs when an element is created. - Attach actions using the
use:directive on elements. - Actions can return an object with a
destroymethod to clean up. - They help keep DOM-related code organized and reusable.