Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

531
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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}

repl link

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!