@@ -16,8 +16,6 @@ import { useVirtualizer } from '@tanstack/react-virtual'
16
16
17
17
import { makeColumns , makeData , Person } from './makeData'
18
18
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.
21
19
function App ( ) {
22
20
const columns = React . useMemo < ColumnDef < Person > [ ] > (
23
21
( ) => makeColumns ( 1_000 ) ,
@@ -36,27 +34,18 @@ function App() {
36
34
37
35
const { rows } = table . getRowModel ( )
38
36
37
+ const visibleColumns = table . getVisibleLeafColumns ( )
38
+
39
39
//The virtualizers need to know the scrollable container element
40
40
const tableContainerRef = React . useRef < HTMLDivElement > ( null )
41
41
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
54
43
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
57
46
getScrollElement : ( ) => tableContainerRef . current ,
58
47
horizontal : true ,
59
- overscan : 3 ,
48
+ overscan : 3 , //how many columns to render on each side off screen each way (adjust this for performance)
60
49
} )
61
50
62
51
//dynamic row height virtualization - alternatively you could use a simpler fixed row height strategy without the need for `measureElement`
0 commit comments