Table input row colour

Hello, I’m trying to set row background colour depending on data category but having issues with passing on the data to a function. Can you help? Ta

viewof bilansx = Inputs.table(bilans, {
   format: { kategoria: bgcol(d => d.kategoria) }
function bgcol(col) {
  return x => htl.html`<div style="
    background: ${col.kategoria === "Wydatki" ? "#fde9d2" : "#a9e4f3"};
    float: left;
    width: 100%; 
    display: block;">${x}`

maybe try this instead:

viewof bilansx = Inputs.table(bilans, {
   format: { kategoria: (d) => bgcol(d.kategoria) }

Thanks but it doesn’t seem to work: Bilans utrzymania pracowni / Aleksander | Observable

Is data used in the table accessible in options as well? Functions here load the data again?

Strangely, I’m seeing the correct output in console but can’t get background to use colour hex string. Any ideas why?

format: {
    kategoria: d => bgcol(d)
function bgcol(d) {
  const col = d === "Wydatki" ? "#fde9d2" : "#a9e4f3";
  return x => htl.html`<div style="
    background: ${col};
    float: left;
    width: 100%; 
    display: block;">${x}`

You don’t need width: 100% or display: block for a div, both are the defaults.

The “easiest” way to do this within the Inputs.table options is to access the entire item from your format callback:

  format: (value, i, rows) => bgcol(rows[i].kategoria) // ...

And then apply that formatter to multiple rows.

I would probably take a mixed approach though that also injects some styles. Let me whip up an example …

The implementation turned out messier than i would have liked, but it works reasonably well. I’ve used a sequential color scale in this demonstration.

Thank you. Well, something’s not right.

This: kategoria: (value, i, rows) => bgcol(rows[i].kategoria)

is the same as this: kategoria: d => bgcol(d)

Right? Both seem to pass correct data onto the function (“Wydatki” and “Wpływy” value).

However, the function fails and is returning the function itself to the cell.

But when I do kategoria: bgcol("Wydatki") then all is fine.

Why is this?

Right now your bgcol() returns a function which only uses the initial argument to bgcol(). Change it to the following and it will work:

bgcol = d => htl.html`<div style="background: ${
  d === "Wydatki" ? oranges(0) : blues(0)

It does work, thanks.

I’ve added an importable helper to the notebook:

import {colorTable} from "@mootari/colored-table-rows"
colorTable(colorData, {
  // Required: Specify the column that contains the color value.
  colorColumn: "rowColor",
  // Optionally specify a color opacity.
  colorOpacity: .3,
  // Any additional table options ...
1 Like