Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

386
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda