reactjsif-statementtailwind-csstextcolor

How to change the element's text color in tailwind when using an if condition in react


I am getting some data from a .json file to a react table. After getting that data , i calculate some data and display in another table cell. What i want is , when calculate those cells , i want the result to change color according to the if condition in tailwind.

For ex: if {item.hisseGuncelFiyat * item.hisseAdet - item.hisseMaliyet * item.hisseAdet < 0 then i want to be red or green

Here is the code:

const Table = () => {

return (
<div className='overflow-auto w-full'>
<table className="  mt-10 w-full ">
  <thead className='bg-blue-900 text-white h-8  '>
    <tr className='divide-x-2 divide-gray-200 '>
      <th>Aracı Kurum</th>
      <th>Hisse Adı</th>
      <th>Maliyet</th>
      <th>Güncel Fiyat</th>
      <th>Adet</th>
      <th>Kar/Zarar</th>
      <th>Düzenle/Sil</th>
    </tr>
  </thead>
  <tbody className='text-center divide-y-2 '>
    {
      data.map((item)=>(
        <tr key={item.hisseId} className=' odd:bg-white even:bg-slate-100  divide-x-2 divide-gray-200'>
        <td className='py-2 whitespace-nowrap'>{item.araciKurum}</td>     
        <td className='py-2 whitespace-nowrap'>{item.hisseAd}</td>
        <td className='py-2 whitespace-nowrap'>{item.hisseMaliyet}<span>₺</span></td>
        <td className='py-2 whitespace-nowrap'>{item.hisseGuncelFiyat}<span>₺</span></td>
        <td className='py-2 whitespace-nowrap'>{item.hisseAdet}</td>
        <td className='py-2 whitespace-nowrap'>
          
          {item.hisseGuncelFiyat * item.hisseAdet - item.hisseMaliyet * item.hisseAdet < 0
           ? "text-red-400"
           : "text-green-400" 
          }
          
          <span>₺</span></td>
        <td className='text-center gap-6 flex justify-center py-2 whitespace-nowrap'>
        <button><BiEdit size={25} className='text-green-500'/></button>
        <button><BiTrashAlt size={25} className='text-red-500'/></button>
      </td>
    </tr>
    )) 
  }
  </tbody>
</table>
</div>
  )
}

I tried something like this but maybe dont know how to write it

<td className='py-2 whitespace-nowrap'>
          
          {item.hisseGuncelFiyat * item.hisseAdet - item.hisseMaliyet * item.hisseAdet < 0
           ? "text-red-400"
           : "text-green-400" 
          }
          
<span>₺</span></td>

Solution

  • You're really close here. Tailwind works through the element's class, so you just need to move your ternary into the className string, like so:

    <td className='py-2 whitespace-nowrap 
      {item.hisseGuncelFiyat * item.hisseAdet - item.hisseMaliyet * item.hisseAdet < 0 
      ? "text-red-400" : "text-green-400" }'>
      <span>
        ₺
      </span>
    </td>
    

    Notice how the ternary statement is inside the className string - that's what you were missing. Other than that, what you have should work.