Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

384
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda