I am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:
I generate rows of a table with an #each
loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).
My idea was to conditionally render different tags based on this value. Like this:
{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}
{#if battery > 70}
<tr >
{:else if battery > 40}
<tr >
{:else }
<tr >
{/if}
But this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.
So is there a good way to change tailwind background color based on a value unpacked in #each
?
CodePudding user response:
I think you should change approach for that problem. You could use the class:name
element directive.
A class: directive provides a shorter way of toggling a class on an element.
Example
{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}
<tr
class:bg-red-500={battery < 39}
class:bg-yellow-500={battery >= 40 && battery < 70}
class:bg-green-500={ battery >= 70}>
<td>{name}/{battery}</td>
</tr>
{/each}