'How to change Tailwind CSS background color with Svelte, based on a value unpacked in #each?

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 class="bg-green-50">
        {:else if battery > 40}
          <tr class="bg-yellow-50">
        {:else }
          <tr class="bg-red-50">
        {/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?



Solution 1:[1]

I would recommend having a function that give you back the background color according to the batteryValue like:

let getBatteryColor = (batteryValue) => {
    if (batteryValue > 70) return 'green'
    if (batteryValue > 40) return 'yellow'
    return 'red'
}

...and then consume it in the node's class:

<tr class={`bg-${getBatteryColor(batteryValue)}`}>
    <td>...</td>
</tr>

Have a look at the REPL.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 johannchopin