0

Given a react-virtualized List with variable content in each row the DOM height needs to be calculated by a rowHeight function - however since that gets called before the row is rendered I am unsure how to actually get the row height.

The examples given for dynamic List row height basically go off a predefined number in the list item's props which doesn't help.

What I think I want to do is render the row on the page at a default height and then get the overflow height on the DOM and set that as the row height. How can I hook into an afterRowRender function or something like that? I imagine performance would suffer so maybe there is a better way of doing this that I am missing.

Simon
  • 1,849
  • 3
  • 22
  • 29
  • 1
    Have you tried `componentDidMount()` life-cycle method? – Cù Đức Hiếu Dec 06 '17 at 15:15
  • Seems like `react-virtualized` have this built in; https://bvaughn.github.io/react-virtualized/#/components/List --- Check: "Use dynamic row height" – TryingToImprove Dec 06 '17 at 15:50
  • Dynamic row height basically toggles the prop `rowHeight` to use a function. However, as I say that function gets called before the row is rendered. – Simon Dec 06 '17 at 16:12

1 Answers1

2

Check out the docs on CellMeasurer. You can see it in action here.

Basically you'll be looking for something like this:

import React from 'react';
import { CellMeasurer, CellMeasurerCache, Grid } from 'react-virtualized';

const cache = new CellMeasurerCache({
  fixedWidth: true,
  minHeight: 50,
});

function rowRenderer ({ index, isScrolling, key, parent, style }) {
  const source // This comes from your list data

  return (
    <CellMeasurer
      cache={cache}
      columnIndex={0}
      key={key}
      parent={parent}
      rowIndex={index}
    >
      {({ measure }) => (
        // 'style' attribute required to position cell (within parent List)
        <div style={style}>
          // Your content here
        </div>
      )}
    </CellMeasurer>
  );
}

function renderList (props) {
  return (
    <List
      {...props}
      deferredMeasurementCache={cache}
      rowHeight={cache.rowHeight}
      rowRenderer={rowRenderer}
    />
  );
}
bvaughn
  • 13,300
  • 45
  • 46
  • I removed my answer considering you are the author of the library. I am curious as to why you would use `CellMeasurer` over `AutoSizer` though. The documentation for `AutoSizer` says that; "This simplifies usage of components like Grid, Table, and List that require explicit dimensions" – Kyle Richardson Dec 06 '17 at 16:22
  • But, fixed width... I want responsive fluid widths for my lists. – Simon Dec 06 '17 at 16:22
  • @KyleRichardson , as I understand it, sizes the actual component, not the child row height. – Simon Dec 06 '17 at 16:23
  • @Simon That makes sense. – Kyle Richardson Dec 06 '17 at 16:24