How to Create Action in Svelte: Syntax and Example
In Svelte, create an
action by defining a function that receives a DOM element and optionally returns an object with lifecycle methods. Use the action by adding use:actionName to an element in your component markup.Syntax
An action in Svelte is a function that takes a DOM element as its first argument. It can return an object with optional update and destroy methods to handle changes and cleanup.
Use the action by adding use:actionName to an HTML element in your Svelte component.
javascript
function actionName(node, parameters) { // setup code here return { update(newParameters) { // handle parameter changes }, destroy() { // cleanup code here } }; } /* Usage in markup */ // <div use:actionName={parameters}></div>
Example
This example creates a simple highlight action that changes the background color of an element. It updates the color if the parameter changes and cleans up on destroy.
svelte
/* highlight.js */ export function highlight(node, color = 'yellow') { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { node.style.backgroundColor = ''; } }; } /* App.svelte */ <script> import { highlight } from './highlight.js'; let color = 'lightblue'; </script> <input type="text" bind:value={color} placeholder="Enter highlight color" /> <p use:highlight={color} tabindex="0">This text is highlighted with the chosen color.</p>
Output
An input box and a paragraph appear. Typing a color name or hex code in the input changes the paragraph's background color in real time.
Common Pitfalls
- Forgetting to return an object with
updateanddestroymethods when needed causes stale behavior or memory leaks. - Not handling parameter changes inside
updatemeans the action won't react to new values. - Using actions on components instead of DOM elements will not work because actions only apply to HTML elements.
javascript
/* Wrong: No cleanup or update */ function badAction(node) { node.style.color = 'red'; } /* Right: Handles updates and cleanup */ function goodAction(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { node.style.color = ''; } }; }
Quick Reference
Svelte Action Cheat Sheet:
function action(node, params): Define your action function.node: The DOM element the action is applied to.params: Optional parameters passed to the action.- Return an object with optional
update(newParams)anddestroy()methods. - Use in markup as
<element use:action={params}></element>.
Key Takeaways
Create an action as a function receiving a DOM element and optional parameters.
Return an object with update and destroy methods to handle changes and cleanup.
Apply actions in markup using the use: directive on HTML elements only.
Always handle parameter updates inside the update method for dynamic behavior.
Clean up side effects in the destroy method to avoid memory leaks.