gregnb / mui-datatables

Datatables for React using Material-UI
MIT License
2.71k stars 931 forks source link

Conditional formatting #1043

Open psaffrey-origami opened 4 years ago

psaffrey-origami commented 4 years ago

Expected Behavior

I'd like to be able to format cells based on the value in it to produce, for example, colour gradients based on values. This is a popular feature in Excel.

Current Behavior

I've found a couple of ways to do this but none are quite satisfactory and I was wondering if there are any other suggestions.

The simple method is to use a customBodyRender and then insert a styled <span> with a background colour. The problem with this approach is that it only colours the little box in the middle of the cell which looks a bit rubbish:

image

The other approach is to use customRowRender, which allows full control over everything so that I can restyle the table elements that own the values, but this means I have to reimplement all the row rendering from scratch including all the nice built-in logic I would usually get for selecting rows:

image

I also wondered whether there was some CSS-based approach but I was unable to come up with one.

(as an aside, I used Chroma to do the colouring and it's really awesome)

Your Environment

Tech Version
Material-UI 4.4.0
MUI-datatables 2.10.2
React 16.9.0
browser
etc
gabrielliwerant commented 4 years ago

Try adding a padding to your <span> in addition to the background color with the customBodyRender. Should fix your issue.

psaffrey-origami commented 4 years ago

Hi @gabrielliwerant , thanks for the suggestion and it certainly looks like a promising approach. The problem with padding the span is that the pad is relative to the span and not the owning td element so it either underfills or overfills the table cell. It's also quite sensitive to the width of the content of the cell, so even if you use percentages you get effects like this:

image

I also tried using a div instead of a span but it didn't seem any better. I will admit that my CSS is pretty weak so I certainly welcome any other expert suggestions you might have.

RyanEwen commented 4 years ago

Kinda hacky but you may be able to use CSS like this:

table td {
  position: relative;
}

table td span.your-classname {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
}