Home > database >  React: Table column cells, conditional formatting with color scale
React: Table column cells, conditional formatting with color scale

Time:04-29

Suppose I have a dataset that should be charted on a table. One column gives a market name, the second gives a market rank.

I'd like the cells in the second column to have a color scale from greatest to least value where greatest is "green" middle is "white" or "transparent" and least value is "red". All in-between values should be shades in-between. Below is an example I'd like to replicate in Excel.

Does anyone know how this can be possible? I gave it a shot in a code sandbox listed below, but was unable to go from green to transparent to red.

Ideal state in Excel

CodePudding user response:

Here's an approach using a pickHex() function that returns a hue between 2 colors based on a weight (ratio).

I've sliced the original array down to 20 entries, to display a smaller table.

Scroll down, to find a link to a live Codesandbox demo.

import original_data from "./testData";

// Source: https://stackoverflow.com/questions/30143082/how-to-get-color-value-from-gradient-by-percentage-with-javascript#answer-30144587
function pickHex(color1, color2, weight) {
  var w1 = weight;
  var w2 = 1 - w1;
  var rgb = [Math.round(color1[0] * w1   color2[0] * w2),
      Math.round(color1[1] * w1   color2[1] * w2),
      Math.round(color1[2] * w1   color2[2] * w2)];
  return rgb;
}

const green = [0,255,0];
const white = [255,255,255];
const red = [255,0,0];

// Green to White: 1 => 0
// console.log( pickHex(green,white, 1) );
// console.log( pickHex(green,white, 0.5) );
// console.log( pickHex(green,white, 0) );

// White top Red: 1 => 0
// console.log( pickHex(white,red, 1) );
// console.log( pickHex(white,red, 0.5) );
// console.log( pickHex(white,red, 0) );

export default function App() {
  const data = original_data.slice(0,20);
  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            <th>Market</th>
            <th>Rank</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item, index) => {
            let backgroundColor;
            const ratio = (index / (data.length / 2 )); 
            if ( ratio > 1 ){
              console.log("We're in the middle...");
              backgroundColor = pickHex(red,white,ratio-1);              
            } else {
              backgroundColor = pickHex(white,green, ratio);              
            }
            backgroundColor = `rgba(${backgroundColor.join(",")})`;
            return (
              <tr key={index}>
                <td>{item.Market}</td>
                <td style={{ backgroundColor }}>
                  {item.CombinedzScore}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

Codesandbox Demo


<script>
  const data = [
    {
      No: "16980",
      Market: "Chicago-Naperville-Elgin, IL-IN-WI",
      CombinedzScore: "131.71"
    },
    {
      No: "31080",
      Market: "Los Angeles-Long Beach-Anaheim, CA",
      CombinedzScore: "128.07"
    },
    {
      No: "35620",
      Market: "New York-Newark-Jersey City, NY-NJ-PA",
      CombinedzScore: "123.41"
    },
    {
      No: "19100",
      Market: "Dallas-Fort Worth-Arlington, TX",
      CombinedzScore: "121.02"
    },
    {
      No: "26420",
      Market: "Houston-The Woodlands-Sugar Land, TX",
      CombinedzScore: "120.88"
    },
    {
      No: "12060",
      Market: "Atlanta-Sandy Springs-Alpharetta, GA",
      CombinedzScore: "120.59"
    },
    {
      No: "19820",
      Market: "Detroit-Warren-Dearborn, MI",
      CombinedzScore: "119.17"
    },
    {
      No: "16740",
      Market: "Charlotte-Concord-Gastonia, NC-SC",
      CombinedzScore: "112.22"
    },
    {
      No: "24860",
      Market: "Greenville-Anderson, SC",
      CombinedzScore: "112.20"
    },
    {
      No: "26900",
      Market: "Indianapolis-Carmel-Anderson, IN",
      CombinedzScore: "112.15"
    }];
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function pickHex(color1, color2, weight) {
  var w1 = weight;
  var w2 = 1 - w1;
  var rgb = [Math.round(color1[0] * w1   color2[0] * w2),
      Math.round(color1[1] * w1   color2[1] * w2),
      Math.round(color1[2] * w1   color2[2] * w2)];
  return rgb;
}

const green = [0,255,0];
const white = [255,255,255];
const red = [255,0,0];

function App() {
  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            <th>Market</th>
            <th>Rank</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item, index) => {
            let backgroundColor;
            const ratio = (index / (data.length / 2 )); 
            if ( ratio > 1 ){
              backgroundColor = pickHex(red,white,ratio-1);                   } else {
              backgroundColor = pickHex(white,green, ratio);                 }
            backgroundColor = `rgba(${backgroundColor.join(",")})`;
            return (
              <tr key={index}>
                <td>{item.Market}</td>
                <td
                  style={{ backgroundColor }}
                >
                  {item.CombinedzScore}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement );
</script>

  • Related