0
0
Svelteframework~30 mins

Action update and destroy in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Svelte Action with Update and Destroy
📖 Scenario: You are building a simple Svelte app that changes the background color of a box when you hover over it. You want to use a Svelte action that updates the color dynamically and cleans up when the box is removed.
🎯 Goal: Create a Svelte action called hoverColor that changes the background color of an element on mouse enter and resets it on mouse leave. The action should support updating the color dynamically and clean up event listeners when the element is removed.
📋 What You'll Learn
Create a Svelte action function named hoverColor that accepts a node and a color parameter.
Add event listeners for mouseenter and mouseleave inside the action.
Implement the update method to change the color dynamically when the parameter changes.
Implement the destroy method to remove event listeners when the element is removed.
Use the hoverColor action on a <div> with an initial color.
💡 Why This Matters
🌍 Real World
Custom Svelte actions help you add reusable interactive behaviors to elements, like hover effects, tooltips, or drag-and-drop, improving user experience.
💼 Career
Understanding Svelte actions with update and destroy methods is important for building maintainable and efficient Svelte applications in professional frontend development.
Progress0 / 4 steps
1
Create the hoverColor action function
Create a Svelte action function called hoverColor that takes node and color as parameters. Inside, add event listeners for mouseenter and mouseleave that change the node's background color to color on mouse enter and reset it to '' on mouse leave.
Svelte
Hint

Remember to define onMouseEnter and onMouseLeave functions inside the action and add event listeners to the node.

2
Add an update method to change the color dynamically
Inside the hoverColor action, add an update method that takes a new color parameter and updates the internal color variable so the hover color changes dynamically.
Svelte
Hint

The update method receives the new parameter and should assign it to the color variable.

3
Add a destroy method to clean up event listeners
Add a destroy method inside the hoverColor action that removes the mouseenter and mouseleave event listeners from the node.
Svelte
Hint

The destroy method should remove the event listeners added earlier to avoid memory leaks.

4
Use the hoverColor action in a Svelte component
In a Svelte component, create a <div> with the text Hover me! and apply the hoverColor action with the initial color 'lightblue'.
Svelte
Hint

Use the Svelte use: directive to apply the hoverColor action to the <div>.