@@ -16,8 +16,6 @@ import { useVirtualizer } from '@tanstack/react-virtual'
1616
1717import { makeColumns , makeData , Person } from './makeData'
1818
19- //This is a dynamic row height example, which is more complicated, but allows for a more realistic table.
20- //See https://tanstack.com/virtual/v3/docs/examples/react/table for a simpler fixed row height example.
2119function App ( ) {
2220 const columns = React . useMemo < ColumnDef < Person > [ ] > (
2321 ( ) => makeColumns ( 1_000 ) ,
@@ -36,27 +34,18 @@ function App() {
3634
3735 const { rows } = table . getRowModel ( )
3836
37+ const visibleColumns = table . getVisibleLeafColumns ( )
38+
3939 //The virtualizers need to know the scrollable container element
4040 const tableContainerRef = React . useRef < HTMLDivElement > ( null )
4141
42- //get first 16 column widths and average them for column size estimation
43- const averageColumnWidth = React . useMemo ( ( ) => {
44- const columnsWidths =
45- table
46- . getRowModel ( )
47- . rows [ 0 ] ?. getCenterVisibleCells ( )
48- ?. slice ( 0 , 16 )
49- ?. map ( cell => cell . column . getSize ( ) ) ?? [ ]
50- return columnsWidths . reduce ( ( a , b ) => a + b , 0 ) / columnsWidths . length
51- } , [ table . getRowModel ( ) . rows ] )
52-
53- //we are using a slightly different virtualization strategy for columns in order to support dynamic row heights
42+ //we are using a slightly different virtualization strategy for columns (compared to virtual rows) in order to support dynamic row heights
5443 const columnVirtualizer = useVirtualizer ( {
55- count : table . getVisibleLeafColumns ( ) . length ,
56- estimateSize : ( ) => averageColumnWidth , //average column width in pixels
44+ count : visibleColumns . length ,
45+ estimateSize : index => visibleColumns [ index ] . getSize ( ) , //estimate width of each column for accurate scrollbar dragging
5746 getScrollElement : ( ) => tableContainerRef . current ,
5847 horizontal : true ,
59- overscan : 3 ,
48+ overscan : 3 , //how many columns to render on each side off screen each way (adjust this for performance)
6049 } )
6150
6251 //dynamic row height virtualization - alternatively you could use a simpler fixed row height strategy without the need for `measureElement`
0 commit comments