|
| 1 | +import * as React from 'react' |
| 2 | +import * as ReactDOM from 'react-dom/client' |
| 3 | + |
| 4 | +import './index.css' |
| 5 | + |
| 6 | +import { useVirtualizer } from '@tanstack/react-virtual' |
| 7 | + |
| 8 | +function App() { |
| 9 | + return ( |
| 10 | + <div> |
| 11 | + <p> |
| 12 | + <strong>Lanes</strong> are useful when you are trying to draw a grid of items, where |
| 13 | + each row is split into multiple columns. |
| 14 | + </p> |
| 15 | + <br /> |
| 16 | + <br /> |
| 17 | + |
| 18 | + <h3>Lanes</h3> |
| 19 | + <LanesVirtualizer /> |
| 20 | + <br /> |
| 21 | + <br /> |
| 22 | + {process.env.NODE_ENV === 'development' ? ( |
| 23 | + <p> |
| 24 | + <strong>Notice:</strong> You are currently running React in |
| 25 | + development mode. Rendering performance will be slightly degraded |
| 26 | + until this application is built for production. |
| 27 | + </p> |
| 28 | + ) : null} |
| 29 | + </div> |
| 30 | + ) |
| 31 | +} |
| 32 | + |
| 33 | +const NUM_LANES = 5 |
| 34 | + |
| 35 | +function LanesVirtualizer() { |
| 36 | + const parentRef = React.useRef(null) |
| 37 | + |
| 38 | + const rowVirtualizer = useVirtualizer({ |
| 39 | + count: 10000, |
| 40 | + getScrollElement: () => parentRef.current, |
| 41 | + estimateSize: () => 35, |
| 42 | + overscan: 5, |
| 43 | + lanes: NUM_LANES, |
| 44 | + }) |
| 45 | + |
| 46 | + return ( |
| 47 | + <> |
| 48 | + <div |
| 49 | + ref={parentRef} |
| 50 | + className="List" |
| 51 | + style={{ |
| 52 | + height: "200px", |
| 53 | + width: "400px", |
| 54 | + overflow: "auto", |
| 55 | + }} |
| 56 | + > |
| 57 | + <div |
| 58 | + style={{ |
| 59 | + height: `${rowVirtualizer.getTotalSize()}px`, |
| 60 | + width: '100%', |
| 61 | + position: 'relative', |
| 62 | + }} |
| 63 | + > |
| 64 | + {rowVirtualizer.getVirtualItems().map((virtualRow) => ( |
| 65 | + <div |
| 66 | + key={virtualRow.index} |
| 67 | + className={virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'} |
| 68 | + style={{ |
| 69 | + position: 'absolute', |
| 70 | + top: 0, |
| 71 | + left: `calc(${virtualRow.index % NUM_LANES} * 100% / ${NUM_LANES})`, |
| 72 | + width: `calc(100% / ${NUM_LANES})`, |
| 73 | + height: `${virtualRow.size}px`, |
| 74 | + transform: `translateY(${virtualRow.start}px)`, |
| 75 | + }} |
| 76 | + > |
| 77 | + Cell {virtualRow.index} |
| 78 | + </div> |
| 79 | + ))} |
| 80 | + </div> |
| 81 | + </div> |
| 82 | + </> |
| 83 | + ) |
| 84 | +} |
| 85 | + |
| 86 | +// eslint-disable-next-line |
| 87 | +ReactDOM.createRoot(document.getElementById('root')!).render( |
| 88 | + <React.StrictMode> |
| 89 | + <App /> |
| 90 | + </React.StrictMode>, |
| 91 | +) |
0 commit comments