React-virtualized: Applying odd element CSS rule to FlexTable row.

Created on 28 May 2016  路  5Comments  路  Source: bvaughn/react-virtualized

I stylize my table with each other row being gray. So (white, gray, white, gray).
I achieve this by using the .Grid_cell:nth-of-type(odd) CSS selector.
However, because of the "only in view" rendering, the "oddness" of a particular row changes depending on the scroll position. This causes the color of the rows to shift as I scroll, and creates a really ugly effect.

Example (compare colors on particular rows):
http://pasteboard.co/1gcyv7SK.png
http://pasteboard.co/1gczQxFw.png

There's a simple fix to this, which is to render rows 2 at a time. If you only render new rows 2 at a time, the "oddness" of a particular row won't change.

Would you mind implementing this feature, either as an option or by default? I think a lot of people stylize their tables this way.

Thank you!

All 5 comments

It's actually pretty easy to accomplish this via JavaScript, as shown in the demo (source).

You could even make a HOC for yourself if you use the functionality in a lot of places:

function FlexTableWrapper ({
  evenClassName,
  headerClassName,
  oddClassName,
  ...props
}) {
  function className({ index }) {
    if (index < 0) {
      return headerClassName || oddClassName
    } else {
      return index % 2 === 0 ? evenClassName : oddClassName
    }
  }

  return (
    <FlexTable
      className={className}
      {...props}
    />
  )
}

I understand that it's simpler to achieve the even/odd styling with pure CSS, but since each new feature adds complexity for me to manage- I avoid adding them if there's a reasonable existing solution.

Hopefully the HOC approach I outlined above will be lightweight enough for you. :)

The solution you propose will cause React to rewrite the class property on each row in the view on each scroll (when element leaves or enters). I understand your point of view, but I think the solution I propose is much cleaner.

Thank you for your solution however, and for your consideration!

It shouldn't, since each rendered row/column uses a React key that combines its row and column index (${rowIndex}-${columnIndex}). This means once the row (or cell) is created initially- with whatever class name you calculate based on its index- it isn't updated while you scroll. New rows are added before/after it depending on your scrolling direction.

It is also possible to fix this with the rowClassName prop on the

component.

Example:

<Table 
      rowClassName={({ index }) => {
          if(index!==-1 && index%2===0) {
            return "even"
          } else if(index!==-1 && index%2===1) {
            return "odd"
          }
</Table>

Official docs can be found here: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md

Was this page helpful?
0 / 5 - 0 ratings