component

Collection


Grid

A Grid is a Grid of Windows. The Grid Grid only renders the cells it needs to fill itself based on the current horizontal/vertical scrolling position.

Props

attribute type Will choose? describe
autoContainerWidth Boolean no Set the internal scrollable container width to auto.
autoHeight Boolean no GridExternal height is set to automatic. This property can only be equal toWindowScrollerUsed in combination with higher-order components
autoWidth Boolean no GridThe outer width is set to automatic. This property can only be equal toWindowScrollerUsed in combination with higher-order components
cellRangeRenderer Function no Responsible for rendering a set of cells with a given index range
cellRenderer Function is The cell responsible for rendering the given column index
className String no Optional custom CSS class name attached to the rootGridOn the element
columnCount Number is Number of grid columns
columnWidth Number or Function is A fixed column width (number) or a function that returns a given index (({index: number}): number) column width. If you use a function, you can specifyestimatedColumnSizeTo optimize the scrolling behavior.
containerProps Object no Responsible for adding attributes tocell-container(e.g. OnWheel event)
containerRole String no cell-ContainerARIA role, default isrowgroup
containerStyle Object no Optional custom inline styles attached to internalcell-containerThe element
deferredMeasurementCache CellMeausrer no ifCellMeasureUsed to calculateGridThe attribute must beCellMeausrerCacheThe pointer. A sharedCellMeasurerCacheReferences to makeGridandCellMeasurerSharing computing data
estimatedColumnSize Number no Used to estimate the entire column before all columns are computedGridThe width of the. The estimated full width will be adjusted after the column is rendered
estimatedRowSize Number no Used to estimate the entire row before all rows are countedGridThe height of the. The estimated full height is adjusted after the line is rendered
height Number is GridThe height of; This property determines the number of rows visible
id String no Optional custom ID to attach to the rootGridThe element
isScrolling Boolean no Overrides whether the interior is in a scrolling state, the entire property mainly servesWindowScrollercomponent
isScrollingOptOut Boolean no Prevents rerendering of visible cells at the scroll end
onContentRenderer Function no Call the callback function with information from the Grid region just rendered, intended to be called when the visible row changes:({columnOverscanStartIndex: number, columnOverscanStopIndex: number, columnStartIndex: number, columnStopIndex: number, rowOverscanStartIndex: number, rowOverscanStopIndex: number, rowStartIndex: number, rowStopIndex: number}): void
onScroll Function no Whenever the scroll offset within the internal scrollable region changes, the callback is called:({ clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }): void
onScrollbarPresenceChange Function no Called whenever a horizontal or vertical scroll bar is added or removed:({ horizontal: boolean, size: number, vertical: boolean }): void
overscanColumnCount Number no Number of columns before and after rendering visible mesh slices. Reduces flicker during scrolling on some browsers or devices.
overscanIndicesGetter Function no Is responsible for counting the number of cells to scan before and after the specified range
overscanRowCount Number no Number of rows before and after rendering visible mesh slices. Reduces flicker during scrolling on some browsers or devices.
role String no Optional override default ARIA, default isgrid
rowCount Number is The number of rows in the grid
rowHeight Number or Function is Fixed line height (number) or the line height that a function returns for a given index:({index: nmber}): number. If using a function, specifyestimatedRowSizeTo optimize the scrolling behavior
scrollingResetTimeInterval Number no Wait for this time after the last scroll event, then reset the grid pointer event; The default value is 150ms.
scrollLeft Number no Horizontal offset
scrollToAlignment String no controlscrolled-to-cellsAlignment of. The default (automatic) scroll to the smallest possible number ensures that the specified cell is fully visible. usestartAssigns the specified cell to the upper left of the grid, usingendAlign to the lower right. usecenterAssigns cells to the middle of the container.
scrollToColumn Number no Ensure that visible column indexes (forced scrolling if necessary) take precedence overscrollLeft
scrollToRow Number no Ensure a visible row index. Prior to thescrollTop
scrollTop Number no Vertical offset
style Object no Optional custom inline style attached to the rootGridThe element
tabIndex Number no Optional override of the default label index. The default is 0
width Nubmer is GridWidth, which determines the number of visible columns


Public methods

  • getOffsetForCell({alignment? : string, coumnIndex? : number, rowIndex? : number})

Gets the offset and alignment of the given cell.

  • getTotalRowsHeight

Gets the estimated height of the entire row.

  • getTotalColumnWidth

Gets the estimated full column width

  • handleScrollEvent({scrollLeft, scrollTop})

This method handles scroll events from external scroll controls. This is an advanced approach, and you probably shouldn’t use it unless you’re implementing a custom scrollbar solution.

  • measureAllCells

All rows and columns in the Grid are expected to be counted.

  • recomputeGridSize({columnIndex: nubmer, rowIndex: number})

Recalculates the row height and column width after specifying the index (default: 0).

This function should be called if the size of a dynamic column or row changes, but nothing else. Because Grid only accepts columnCount and rowCount, it cannot detect when the underlying data changes.

This method also enforces a rendering cycle (via forceUpdate) to ensure that updated measurements are reflected in the rendered mesh.

  • scrollToCell(columnIndex: number, rowIndex: number)

Make sure rows and columns are visible. This method can be used to safely roll back to a cell after the user scrolls away from it. Even if you’ve rolled to the wrong position.

  • scrollToPosition({scrollLeft, scrollTop})

Scroll to specify the offset. Animation for setting position changes.


The name of the class

The Grid component supports the following static class names:

attribute describe
ReactVirtualized__Grid (External) Main element
ReactVirtualizedGridinnerScrollContainer Inner rolling area


cellRangeRenderer

This is an advanced property. It is useful in cases where the grid needs other overridden UIs, such as gantt charts or calendar applications. Many use cases can be solved more easily using the onScroll callback or ScrollSync advanced component.

If you want to rewrite cellRangeRenderer, the easiest way is to enhance the default implementation:

import {defaultCellRangeRenderer, Grid} from 'react-virtualized';

function cellRangeRenderer(props) {
  const children = defaultCellRangeRenderer(props);
  children.push(<div>My custom overlay</div>);
  return children;
}

function CustomizedGrid(props) {
  return <Grid cellRangeRenderer={cellRangeRenderer} {. props} / >;
}
Copy the code

If greater customization is required, the defaultCellRangeRenderer function may need to be derived.

This function takes the following named arguments:

function cellRangeRenderer({
  cellCache, // Temporary cell cache used while scrolling
  cellRenderer, // Cell renderer prop supplied to Grid
  columnSizeAndPositionManager, // @see CellSizeAndPositionManager,
  columnStartIndex, // Index of first column (inclusive) to render
  columnStopIndex, // Index of last column (inclusive) to render
  horizontalOffsetAdjustment, // Horizontal pixel offset (required for scaling)
  isScrolling, // The Grid is currently being scrolled
  rowSizeAndPositionManager, // @see CellSizeAndPositionManager,
  rowStartIndex, // Index of first row (inclusive) to render
  rowStopIndex, // Index of last row (inclusive) to render
  scrollLeft, // Current horizontal scroll offset of Grid
  scrollTop, // Current vertical scroll offset of Grid
  styleCache, // Temporary style (size & position) cache used while scrolling
  verticalOffsetAdjustment, // Vertical pixel offset (required for scaling)
}) {
  const renderedCells = [];

  for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) {
    // This contains :offset (top) and :size (height) information for the cell
    let rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex);

    for (
      let columnIndex = columnStartIndex;
      columnIndex <= columnStopIndex;
      columnIndex++
    ) {
      // This contains :offset (left) and :size (width) information for the cell
      let columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(
        columnIndex,
      );

      // Be sure to adjust cell position in case the total set of cells is too large to be supported by the browser natively.
      // In this case, Grid will shift cells as a user scrolls to increase cell density.
      let left = columnDatum.offset + horizontalOffsetAdjustment;
      let top = rowDatum.offset + verticalOffsetAdjustment;

      // The rest of the information you need to render the cell are contained in the data.
      // Be sure to provide unique :key attributes.
      let key = `${rowIndex}-${columnIndex}`;
      let height = rowDatum.size;
      let width = columnDatum.size;

      // Now render your cell and additional UI as you see fit.
      // Add all rendered children to the :renderedCells Array.}}return renderedCells;
}
Copy the code


overscanIndicesGetter

This is an advanced property. This function counts the number of cells scanned before and after the specified range. By default, React – Virtualized optimizes the number of units to be scanned based on the rolling direction. If you want to customize the behavior, can forkdefaultOverscanIndicesGetter function.

function overscanIndicesGetter ({
  direction,          // One of "horizontal" or "vertical"
  cellCount,          // Number of rows or columns in the current axis
  scrollDirection,    // 1 (forwards) or -1 (backwards)
  overscanCellsCount, // Maximum number of cells to over-render in either direction
  startIndex,         // Begin of range of visible cells
  stopIndex           // End of range of visible cells
}) {
  return {
    overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
    overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount)
  }
}
Copy the code


cellRender

Responsible for rendering a single cell, giving an index of rows and columns. This function takes the following named arguments:

function cellRenderer({
  columnIndex, // Horizontal (column) index of cell
  isScrolling, // The Grid is currently being scrolled
  isVisible, // This cell is visible within the grid (eg it is not an overscanned cell)
  key, // Unique key within array of cells
  parent, // Reference to the parent Grid (instance)
  rowIndex, // Vertical (row) index of cell
  style, // Style object to be applied to cell (to position it);
  // This must be passed through to the rendered cell element.
}) {
  // Grid data is a 2d array in this example...
  const user = list[rowIndex][columnIndex];

  // If cell content is complex, consider rendering a lighter-weight placeholder while scrolling.
  const content = isScrolling ? '... ' : <User user={user} />;

  // Style is required since it specifies how the cell is to be sized and positioned.
  // React Virtualized depends on this sizing/positioning for proper scrolling behavior.
  // By default, the grid component provides the following style properties:
  // position
  // left
  // top
  // height
  // width
  // You can add additional class names or style properties as you would like.
  // Key is also required by React to more efficiently manage the array of cells.
  return (
    <div key={key} style={style}>
      {content}
    </div>
  );
}
Copy the code


The basis ofGridThe sample

Here is a very basic Grid example. This grid shows a group of objects with a fixed row size. Dynamic is also supported.

import React from 'react';
import ReactDOM from 'react-dom';
import {Grid} from 'react-virtualized';

// Grid data as an array of arrays
const list = [
  ['Brian Vaughn'.'Software Engineer'.'San Jose'.'CA'.95125 / *... * /].// And so on...
];

function cellRenderer({columnIndex, key, rowIndex, style}) {
  return (
    <div key={key} style={style}>
      {list[rowIndex][columnIndex]}
    </div>
  );
}

// Render your grid
ReactDOM.render(
  <Grid
    cellRenderer={cellRenderer}
    columnCount={list[0].length}
    columnWidth={100}
    height={300}
    rowCount={list.length}
    rowHeight={30}
    width={300}
  />.document.getElementById('example'));Copy the code





List


Table

  • Column

  • SortDirection




High order component


ArrowKeyStepper


AutoSizer


CellMeasurer

CellMeasurer is a high-level component that automatically calculates cell contents through a rendering method that is not visible to the user. You can specify a fixed width to calculate the dynamic height (and vice versa). This is an advanced component with some limitations and performance considerations.

CellMeasurer can be used with Grid, List, and Table components, but not with Collections.


Props

attribute type Will choose? describe
cache CellMeasurerCache is inCellMeasureAnd their fathersGridCache shared between
children Element or Function is It can be a React element (for example<div />) or a function

(e.g.({measure, registerChild}) => <div ref={registerChild} />)
columnIndex number is The computed column index (at parent levelGridIn) or 0 (useListorTable)
parent Grid is The parentGridThe reference; Change the value is madeGridPassed to thecellRenderer, should be passed as is
rowIndex number is Computed row index (at parent levelGridIn)


Render Props

attribute type describe
measure Function Perform cell calculation
registerChild Function Specifies the Dom element to evaluate, which can be used asref(the default isWindowScrolleruseReactDOM.findDOMNodeFunction)


CellMeasurerCache

CellMeasurerCache stores CellMeasurer calculations and shares them with a parent Grid. It should be configured based on the type of computation you need. The following parameters are accepted:

attribute type Will choose? describe
defaultHeight number no Uncalculated cells will be changed to the initial height
defaultWidth number no Uncalculated cells will be changed to initialize the width
fixedHeight number no Render cells will have a fixed height, dynamic width
fixedWidth number no Render cells will have a fixed width, dynamic height
minHeight number no The derived row height of multiple cells should not be less than the changed value
minWidth number no The derived column width of multiple cells should not be smaller than the changed value
keyMapper number no You can more intelligently map a given column and row index to a project ID. This prevents cell cache invalidation when the parent is modified.(rowIndex: number, columnIndex: number) => any

Note that all of the above attributes are optional and you must provide at least some of them. CellMeasureerCache is not meant to calculate dynamic width and height at the same time. This is inefficient when the size of the row (or column) is equal to the size of the largest cell in the row.


CellMeasurerCacheGeneral method

  • clear(rowIndex: number, columnIndex: number)

Resets the calculation cache for a specified cell

Should be called when a cell needs to be recalculated to handle dynamic content. (such as replacing load ICONS with loaded content or responding to state changes in stateful cells)

  • clearAll()

Reset the calculation cache for all cells

It should be called when the Grid, List, and Table components need to be recycled due to resize events triggered by reactive layouts. (For example, changing the window size requires a cell height response)


example

  • Grid

This example shows a Grid with a fixed row height and a dynamic column width.

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

// In this example, average cell width is assumed to be about 100px.
// This value will be used for the initial `Grid` layout.
// Cell measurements smaller than 75px should also be rounded up.
// Height is not dynamic.
const cache = new CellMeasurerCache({
  defaultWidth: 100.minWidth: 75.fixedHeight: true
});

function cellRenderer ({ columnIndex, key, parent, rowIndex, style }) {
  const content // Derive this from your data somehow

  return (
    <CellMeasurer
      cache={cache}
      columnIndex={columnIndex}
      key={key}
      parent={parent}
      rowIndex={rowIndex}
    >
      <div
        style={{
          . style.height: 35.whiteSpace: 'nowrap'}} >
        {content}
      </div>
    </CellMeasurer>
  );
}

function renderGrid (props) {
  return (
    <Grid
      {. props}
      columnWidth={cache.columnWidth}
      deferredMeasurementCache={cache}
      cellRenderer={cellRenderer}
    />
  );
}
Copy the code
  • useregisterChild

CellMeasurer uses findDOMNode by default to retrieve DOM elements for calculation. However, this API is not recommended in React strict mode. So you might want to avoid this usage. Instead, you can use the registerChild attribute to specify the element. (for example, passing it in as a ref)

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

// In this example, average cell width is assumed to be about 100px.
// This value will be used for the initial `Grid` layout.
// Cell measurements smaller than 75px should also be rounded up.
// Height is not dynamic.
const cache = new CellMeasurerCache({
  defaultWidth: 100.minWidth: 75.fixedHeight: true
});

function cellRenderer ({ columnIndex, key, parent, rowIndex, style }) {
  const content // Derive this from your data somehow

  return (
    <CellMeasurer
      cache={cache}
      columnIndex={columnIndex}
      key={key}
      parent={parent}
      rowIndex={rowIndex}
    >
      {({registerChild}) => (
        <div
          style={{
            . style.height: 35.whiteSpace: 'nowrap'}} >
          {content}
        </div>
      )}
    </CellMeasurer>
  );
}

function renderGrid (props) {
  return (
    <Grid
      {. props}
      columnWidth={cache.columnWidth}
      deferredMeasurementCache={cache}
      cellRenderer={cellRenderer}
    />
  );
}
Copy the code
  • Use with picturesCellMeasurer

This example shows how to use the CellMeasurer component with the List component to display dynamic height rows. Unlike the example above, the line height is determined after the image data has been loaded. A function is passed to the CellMeasurer component to do this, taking both measure and registerChild parameters. Measure should be called after the cell contents have been calculated. (In this case, after the image data is loaded)

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

// In this example, average cell height is assumed to be about 50px.
// This value will be used for the initial `Grid` layout.
// Width is not dynamic.
const cache = new CellMeasurerCache({
  defaultHeight: 50.fixedWidth: true
});

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, registerChild }) => (
        // 'style' attribute required to position cell (within parent List)
        <div ref={registerChild} style={style}>
          <img
            onLoad={measure}
            src={source}
          />
        </div>
      )}
    </CellMeasurer>
  );
}

function renderList (props) {
  return (
    <List
      {. props}
      deferredMeasurementCache={cache}
      rowHeight={cache.rowHeight}
      rowRenderer={rowRenderer}
    />
  );
}
Copy the code
  • Use one that has the same dynamic cell height or widthCellMeasurer
// Normally, every cell gets measured individually and is very slow.
// However, with the keyMapper prop we can specify a constant return value and
// tell CellMeasurer that all measurements after the first one will hit the
// cache and we get a speedy solution.
const cache = new CellMeasurerCache({
  defaultHeight: 30.fixedWidth: true.keyMapper: () = > 1});Copy the code


Limitations and performance considerations

Calculating the column width requires counting all rows to determine the maximum width at which the column occurs. The same goes for calculating row heights. So it’s not a good idea to use higher-order components of the Grid when both columns and cells contain large amounts of data.

Since this component only calculates the width and height of one cell at a time, it will be slow if the user skips over many rows (or columns) at once with the scrollbar or scoll-to-cell property. Unfortunately, there is no solution for this performance limitation.


ColumnSizer


InfiniteLoader


MultiGrid


ScrollSync


WindowScroller




Getting started guide