Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure a rows height in react-virtualized list

I'm a little uncertain as how to achieve dynamic heights of a List using react-virtualized.

I have a component as follows:

import { List } from 'react-virtualized';
<List
    height={400}
    rowCount={_.size(messages)}
    rowHeight={(index) => {
        return 100; // This needs to measure the dom.
    }}
    rowRenderer={({ key, index, style }) => <Message style={style} {...messages[index]} />}}
    width={300}
/>

I have looked at using CellMeasurer as per the docs which says it can be used with the List component but I have no idea how this example actually works...

I've also tried to work out how it has been achieved in the demo code but have also reached a dead end.

Can someone please assist me on how I would measure the DOM to get each items height dynamically.

like image 776
Matt Derrick Avatar asked Sep 20 '16 17:09

Matt Derrick


1 Answers

Sorry you found the docs to be confusing. I will try to update them to be clearer. Hopefully this will help:

import { CellMeasurer, List } from 'react-virtualized';

function renderList (listProps) {
  return (
    <CellMeasurer
      cellRenderer={
        // CellMeasurer expects to work with a Grid
        // But your rowRenderer was written for a List
        // The only difference is the named parameter they
        // So map the Grid params (eg rowIndex) to List params (eg index)
        ({ rowIndex, ...rest }) => listProps.cellRenderer({ index: rowIndex, ...rest })
      }
      columnCount={1}
      rowCount={listProps.rowCount}
      width={listProps.width}
    >
      {({ getRowHeight, setRef }) => (
        <List
          {...listProps}
          ref={setRef}
          rowHeight={getRowHeight}
        />
      )}
    </CellMeasurer>
  )
}

There are also demos of this component here showing how it's used.

like image 58
bvaughn Avatar answered Oct 06 '22 00:10

bvaughn