Performance: Conditional classes (class:name)
This affects how CSS classes are applied dynamically during rendering, impacting style recalculation and layout.
<div class:active={isActive}></div><div class={isActive ? 'active' : ''}></div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| class={condition ? 'className' : ''} | 1 attribute update | 1 style recalculation, possible reflow | medium paint cost | [X] Bad |
| class:name={condition} | 1 class toggle | 1 style recalculation, no reflow | low paint cost | [OK] Good |
class:active={isActive} do in a component?class:name={condition}name only when the condition is true.class:active={isActive}active is added only if isActive is true; otherwise, it is not added.highlight in Svelte when isHighlighted is true?class:name={condition} without spaces around the equals sign.class:highlight={isHighlighted} matches the correct syntax exactly: class:highlight={isHighlighted}. Others have syntax errors or invalid formats.<script>
let isError = false;
</script>
<div class:error={isError} class:success={!isError}>Status</div>isError is false?class:error={isError} when isError is falseisError is false, the class error is not added.class:success={!isError} when isError is false!isError is true, so the class success is added.<script>
let isActive = true;
</script>
<button class:active = {isActive}>Click Me</button>isActive is declared correctly in the script block.class:active = {isActive} has spaces around the equals sign, which is invalid in Svelte. It should be class:active={isActive} without spaces.visible and highlight to a <div> in Svelte. visible should be added when isVisible is true, and highlight only when isHighlighted is also true and isVisible is true.visible depends only on isVisible. The class highlight depends on both isHighlighted and isVisible being true.<div class:visible={isVisible} class:highlight={isHighlighted && isVisible}>Content</div> correctly uses class:visible={isVisible} and class:highlight={isHighlighted && isVisible}, matching the requirements. <div class:visible={isVisible} class:highlight={isHighlighted || isVisible}>Content</div> uses OR which is incorrect. <div class:visible={isVisible && isHighlighted} class:highlight={isVisible}>Content</div> swaps conditions incorrectly. <div class:visible={isVisible} class:highlight={isHighlighted}>Content</div> misses the isVisible condition for highlight.Pass the test and this pattern moves unknown