Challenge - 5 Problems
Svelte Action Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediateWhat is the output when using an action with parameters in Svelte?
Consider this Svelte action that changes the background color of an element based on a parameter. What will be the background color of the
after mounting?
function colorAction(node, color) {
node.style.backgroundColor = color;
return {
update(newColor) {
node.style.backgroundColor = newColor;
}
};
}
<div use:colorAction={'red'}>Hello</div>Svelte
function colorAction(node, color) { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; } }; } <div use:colorAction={'red'}>Hello</div>
Attempts:
2 left
💡 Hint
Remember that the action receives the parameter as the second argument and applies it immediately.
✗ Incorrect
The action receives 'red' as the color parameter and sets the node's background color to red on mount.
❓ state_output
intermediateHow does updating action parameters affect the DOM in Svelte?
Given this Svelte action and component, what will be the background color of the
after the button is clicked?
function colorAction(node, color) {
node.style.backgroundColor = color;
return {
update(newColor) {
node.style.backgroundColor = newColor;
}
};
}
<script>
let bg = 'blue';
</script>
<div use:colorAction={bg}>Color me</div>
<button on:click={() => bg = 'green'}>Change Color</button>Svelte
function colorAction(node, color) { node.style.backgroundColor = color; return { update(newColor) { node.style.backgroundColor = newColor; } }; } <script> let bg = 'blue'; </script> <div use:colorAction={bg}>Color me</div> <button on:click={() => bg = 'green'}>Change Color</button>
Attempts:
2 left
💡 Hint
Check how the action's update method reacts to parameter changes.
✗ Incorrect
When the variable 'bg' changes, Svelte calls the action's update method with the new value, updating the background color.
📝 Syntax
advancedWhich option correctly defines a Svelte action with parameters and cleanup?
You want to create a Svelte action that logs a message when the element is mounted and removes the event listener on destroy. Which code snippet is correct?
Attempts:
2 left
💡 Hint
Remember to keep a reference to the event handler to remove it later.
✗ Incorrect
Option A correctly stores the handler function and removes it in destroy. Others either miss the handler reference or don't remove the listener properly.
🔧 Debug
advancedWhy does this Svelte action not update when parameters change?
Examine this Svelte action usage:
Why does the border not update when clicking the button?
function borderAction(node, width) {
node.style.border = width + 'px solid black';
}
<script>
let borderWidth = 2;
</script>
<div use:borderAction={borderWidth}>Box</div>
<button on:click={() => borderWidth = 5}>Increase Border</button>Why does the border not update when clicking the button?
Svelte
function borderAction(node, width) { node.style.border = width + 'px solid black'; } <script> let borderWidth = 2; </script> <div use:borderAction={borderWidth}>Box</div> <button on:click={() => borderWidth = 5}>Increase Border</button>
Attempts:
2 left
💡 Hint
Check if the action handles changes to its parameters after initial mount.
✗ Incorrect
Without an update method, the action only runs once on mount and ignores parameter changes.
🧠 Conceptual
expertWhat happens if an action's update method returns a new destroy function in Svelte?
In Svelte, an action can return an object with update and destroy methods. What is the effect if the update method returns a new destroy function?
Consider:
Consider:
function exampleAction(node, param) {
const cleanup = () => console.log('cleanup old');
node.style.color = param;
return {
update(newParam) {
cleanup();
node.style.color = newParam;
return () => console.log('cleanup new');
},
destroy() {
console.log('destroy called');
}
};
}Svelte
function exampleAction(node, param) { const cleanup = () => console.log('cleanup old'); node.style.color = param; return { update(newParam) { cleanup(); node.style.color = newParam; return () => console.log('cleanup new'); }, destroy() { console.log('destroy called'); } }; }
Attempts:
2 left
💡 Hint
Think about how Svelte manages cleanup between updates and unmount.
✗ Incorrect
When update returns a function, Svelte treats it as a cleanup function replacing the previous one, calling it before the next update or destroy.
Practice
1. What is the purpose of passing parameters to a Svelte action using
use:action={parameter}?easy
Solution
Step 1: Understand action parameters
Action parameters allow you to send extra data to a Svelte action to customize its behavior.Step 2: Identify the purpose of
This syntax passes the parameter to the action so it can use it internally.use:action={parameter}Final Answer:
To customize the behavior of the action with extra data -> Option BQuick Check:
Action parameters customize behavior = A [OK]
Hint: Parameters customize actions with extra data [OK]
Common Mistakes:
- Thinking parameters define components
- Confusing parameters with styling
- Assuming parameters import libraries
2. Which of the following is the correct syntax to pass a parameter named
color with value 'red' to a Svelte action called highlight?easy
Solution
Step 1: Recall correct parameter passing syntax
Svelte actions receive parameters usinguse:action={parameter}where parameter can be any value or object.Step 2: Identify correct object syntax for passing color
To pass an object with a keycolorand value'red', use{color: 'red'}inside curly braces.Final Answer:
use:highlight={{color: 'red'}} -> Option AQuick Check:
Pass object with color key = D [OK]
Hint: Use curly braces with object for named parameters [OK]
Common Mistakes:
- Using parentheses instead of curly braces
- Passing string directly without braces
- Passing variable without defining it
3. Given this Svelte action:
What will be the border color after this code runs?
function border(node, { color }) {
node.style.border = `2px solid ${color}`;
return {
update({ color }) {
node.style.border = `2px solid ${color}`;
}
};
}What will be the border color after this code runs?
<div use:border={{ color: 'blue' }}>Box</div>medium
Solution
Step 1: Understand initial border style setting
The action sets the border style to '2px solid' plus the passed color, which is 'blue'.Step 2: Confirm the border color after applying the action
The div will have a blue border because the parameter color is 'blue' and the style is applied immediately.Final Answer:
A 2px solid blue border -> Option AQuick Check:
Passed color 'blue' sets border color = B [OK]
Hint: Action sets style using passed color parameter [OK]
Common Mistakes:
- Assuming default color instead of passed color
- Ignoring the update method
- Thinking no border is set initially
4. Consider this Svelte action code:
Which of the following will result in an invalid CSS transform value when used as
function scale(node, factor) {
node.style.transform = `scale(${factor})`;
return {
update(newFactor) {
node.style.transform = `scale(${newFactor})`;
}
};
}Which of the following will result in an invalid CSS transform value when used as
use:scale={...}?medium
Solution
Step 1: Analyze expected parameter type
The action expects a single number parameterfactor, not an object.Step 2: Identify which option passes an object instead of a number
use:scale={{ factor: 2 }} passes an object{ factor: 2 }, which will causescale(${newFactor})to becomescale([object Object]), an invalid CSS transform value.Final Answer:
use:scale={{ factor: 2 }} -> Option CQuick Check:
Passing object instead of number causes invalid transform = C [OK]
Hint: Match parameter type expected by action exactly [OK]
Common Mistakes:
- Passing object when number expected
- Passing string instead of number (allowed but may cause visual issues)
- Passing objects when primitive expected
5. You want to create a Svelte action
tooltip that shows a message passed as a parameter and updates the message if it changes. Which of these implementations correctly handles parameter updates?hard
Solution
Step 1: Check for update method handling parameter changes
function tooltip(node, message) { const tip = document.createElement('span'); tip.textContent = message; node.appendChild(tip); return { update(newMessage) { tip.textContent = newMessage; }, destroy() { node.removeChild(tip); } }; }defines anupdatemethod that updates the tooltip text when the parameter changes.Step 2: Verify cleanup with destroy method
This implementation also defines adestroymethod to remove the tooltip element when the action is removed, which is good practice.Final Answer:
The implementation withupdateanddestroymethods -> Option DQuick Check:
Update method handles parameter changes = A [OK]
Hint: Use update and destroy methods to handle changes and cleanup [OK]
Common Mistakes:
- Not implementing update method for parameter changes
- Not cleaning up DOM elements on destroy
- Using incorrect element types or missing return object
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
