How To Change Color Of <td> element depending on value

Viewed 424

I am currently trying to change the color of a element in the table depending on if the value is positive or negative, currently this is what I have but it is not working properly and is n^2 which I find sort of inefficient:

export const ActiveStockList = () => {
  const store = useStockListStore();

  var x = document.getElementsByClassName("ColorTest");
  for (var i = 0; i < x.length; i++) {
    for (var j = 0; j < x[i].length; j++) {
      if (x[i].charAt(j) != "-") {
        x[i].style.Color = "green";
      } else {
        x[i].style.Color = "red";
      }
    }
  }

  return useObserver(() =>
    store.stocks.map((stock) => (
      <tr>
        <td className="justify-content-center">
          <a href={"/stocks/" + stock.symbol}>{stock.symbol}</a>
        </td>
        <td>{+stock.latestVolume}</td>
        <td className="ColorTest">
          {(+stock.changePercent * 100).toFixed(2)}%
        </td>
        <td className="ColorTest">$ {+stock.change}</td>
        <td>$ {+stock.latestPrice}</td>
        <td className="ColorTest">{(+stock.ytdChange * 100).toFixed(2)}%</td>
        <td>Buy</td>
        <td>10,023,000</td>
        <td>89.23</td>
        <td>140,000</td>
      </tr>
    ))
  );
};

what is the best way to change the three elements to either green or red depending if their value is greater than 0 or less than 0? Thank you!

2 Answers

My suggestion. Write it as an inline style. No need to modify the dom the way you are doing it with React. Use the actual number and a logic check:

style={stockNumber <= 0 ? {color: "red"} : {color: "green"}}

Or whatever logic. Turn it into a function that returns the style object if you don't want to repeat the logic over and over.

It doesn't really make sense to set the colors by iterating over the matching elements.

You can just set the style attribute in-place.

For example, instead of

<td className="ColorTest">$ {+stock.change}</td>

you could have:

<td style={{ color: stock.change < 0 ? "red" : "green"}}>$ {+stock.change}</td>
Related