Home > Blockchain >  Add image/button to React bootstrap table cell based on value of cell
Add image/button to React bootstrap table cell based on value of cell

Time:03-28

UPDATE: Here is a enter image description here

I have a bootstrap table with these columns: name, expDate, stoplight. The value in the stoplight column is based on the date in the expDate column. If the expDate is within 7 days of today it's red, between 7 and 21 days it's Yellow, and otherwise Green, see logic below. If all I want is to display the words, Red, Yellow, Green it works fine. The part where I'm getting stuck is I want to display a 'stoplight', a red or yellow or green circle/button in the column. I have a working css but I cannot figure out how to apply a custom format to a specific cell. Any help is appreciated.

    <BootstrapTable
      keyField="street"
      columns={columns}
      data={rows}
      hover
      rowEvents={tableRowEvents}
      bordered={true}
      rowStyle={rowStyle}
    />

const Stoplight = (daysToExpDate) => { 
      if (daysToExpDate <= 7) {
        return "Red"; 
      } else if (daysToExpDate > 30) {
        return "Green"; 
      } else {
        return "Yellow"; 
      }
    };

And here is my rudimentary css that works by itself but not in the table.

.redlight {
  border-radius: 50%;
  color: red;
  background-color: red;
}
.greenlight {
  border-radius: 50%;
  color: green;
  background-color: green;
}
.yellowlight {
  border-radius: 50%;
  color: yellow;
  background-color: yellow;
}

This row style highlights the entire row, not just the cell in question.

const rowStyle = (row, rowIndex) => {
    const style = {};
    if (row.stoplight === "Red") {
      style.backgroundColor = "Red";
    } else if (row.stoplight === "Green") {
      style.backgroundColor = "Green";
    } else {
      style.backgroundColor = "Yellow";
    }

    if (rowIndex > 2) {
      style.fontWeight = "normal";
      style.color = "black";
    }

    return style;
  };

CodePudding user response:

You can pass a div element as data

const data = [{
        name: "884 Restbrook Ave",
        expDate: "2022-06-01",
        light: <div className = "circle green"> </div>
    },
    {
        name: "2587 Wellons Ave",
        expDate: "2023-04-24",
        light: <div className = "circle yellow"> </div>
    },
    {
        name: "3948 Boulevard Pl",
        expDate: "2022-03-26",
        light: <div className = "circle red"> </div>
    }
];

and apply a nice css to this

.circle {
  width: 15px;
  height: 15px;
  border-radius: 15px;
}

.green {
  background: olivedrab;
}

.red {
  background: maroon;
}

.yellow {
  background: darkgoldenrod;
}
  • Related