|
| 1 | +import React from 'react' |
| 2 | +import ReactDOM from 'react-dom/client' |
| 3 | +import { |
| 4 | + columnResizingFeature, |
| 5 | + columnSizingFeature, |
| 6 | + createColumnHelper, |
| 7 | + tableFeatures, |
| 8 | + useTable, |
| 9 | +} from '@tanstack/react-table' |
| 10 | +import { makeData } from './makeData' |
| 11 | +import type { Person } from './makeData' |
| 12 | +import './index.css' |
| 13 | + |
| 14 | +const _features = tableFeatures({ columnSizingFeature, columnResizingFeature }) |
| 15 | + |
| 16 | +const columnHelper = createColumnHelper<typeof _features, Person>() |
| 17 | + |
| 18 | +const columns = columnHelper.columns([ |
| 19 | + columnHelper.accessor('firstName', { |
| 20 | + cell: (info) => info.getValue(), |
| 21 | + header: 'First Name', |
| 22 | + size: 150, |
| 23 | + }), |
| 24 | + columnHelper.accessor('lastName', { |
| 25 | + cell: (info) => info.getValue(), |
| 26 | + header: 'Last Name', |
| 27 | + size: 150, |
| 28 | + }), |
| 29 | + columnHelper.accessor('age', { |
| 30 | + header: 'Age', |
| 31 | + size: 80, |
| 32 | + }), |
| 33 | + columnHelper.accessor('visits', { |
| 34 | + header: 'Visits', |
| 35 | + size: 100, |
| 36 | + }), |
| 37 | + columnHelper.accessor('status', { |
| 38 | + header: 'Status', |
| 39 | + size: 150, |
| 40 | + }), |
| 41 | + columnHelper.accessor('progress', { |
| 42 | + header: 'Profile Progress', |
| 43 | + size: 180, |
| 44 | + }), |
| 45 | +]) |
| 46 | + |
| 47 | +function App() { |
| 48 | + const [data] = React.useState(() => makeData(20)) |
| 49 | + const tableContainerRef = React.useRef<HTMLDivElement>(null) |
| 50 | + const [containerWidth, setContainerWidth] = React.useState(0) |
| 51 | + |
| 52 | + // Track container width with ResizeObserver |
| 53 | + React.useEffect(() => { |
| 54 | + const container = tableContainerRef.current |
| 55 | + if (!container) return |
| 56 | + |
| 57 | + const observer = new ResizeObserver((entries) => { |
| 58 | + for (const entry of entries) { |
| 59 | + setContainerWidth(entry.contentRect.width) |
| 60 | + } |
| 61 | + }) |
| 62 | + observer.observe(container) |
| 63 | + return () => observer.disconnect() |
| 64 | + }, []) |
| 65 | + |
| 66 | + const table = useTable( |
| 67 | + { |
| 68 | + _features, |
| 69 | + _rowModels: {}, |
| 70 | + columns, |
| 71 | + data, |
| 72 | + defaultColumn: { |
| 73 | + minSize: 50, |
| 74 | + maxSize: 800, |
| 75 | + }, |
| 76 | + columnResizeMode: 'onChange', |
| 77 | + }, |
| 78 | + (state) => ({ |
| 79 | + columnSizing: state.columnSizing, |
| 80 | + columnResizing: state.columnResizing, |
| 81 | + }), |
| 82 | + ) |
| 83 | + |
| 84 | + const visibleColumns = table.getVisibleLeafColumns() |
| 85 | + const totalColumnsWidth = table.getTotalSize() |
| 86 | + |
| 87 | + // Determine if the last column should stretch to fill remaining space |
| 88 | + const shouldExtendLastColumn = totalColumnsWidth < containerWidth |
| 89 | + |
| 90 | + // Compute the width for each column, stretching the last one if needed |
| 91 | + const getColumnWidth = React.useCallback( |
| 92 | + (columnId: string, index: number, baseWidth: number) => { |
| 93 | + if (shouldExtendLastColumn && index === visibleColumns.length - 1) { |
| 94 | + const otherColumnsWidth = visibleColumns |
| 95 | + .slice(0, -1) |
| 96 | + .reduce((sum, col) => sum + col.getSize(), 0) |
| 97 | + return Math.max(baseWidth, containerWidth - otherColumnsWidth) |
| 98 | + } |
| 99 | + return baseWidth |
| 100 | + }, |
| 101 | + [shouldExtendLastColumn, visibleColumns, containerWidth], |
| 102 | + ) |
| 103 | + |
| 104 | + // Pre-compute column sizes as CSS variables for performant resizing |
| 105 | + const columnSizeVars = React.useMemo(() => { |
| 106 | + const headers = table.getFlatHeaders() |
| 107 | + const colSizes: Record<string, number> = {} |
| 108 | + for (let i = 0; i < headers.length; i++) { |
| 109 | + const header = headers[i] |
| 110 | + const width = getColumnWidth( |
| 111 | + header.column.id, |
| 112 | + i, |
| 113 | + header.column.getSize(), |
| 114 | + ) |
| 115 | + colSizes[`--header-${header.id}-size`] = width |
| 116 | + colSizes[`--col-${header.column.id}-size`] = width |
| 117 | + } |
| 118 | + return colSizes |
| 119 | + }, [table.state.columnResizing, table.state.columnSizing, getColumnWidth]) |
| 120 | + |
| 121 | + // Table width: always at least the container width |
| 122 | + const tableWidth = Math.max(totalColumnsWidth, containerWidth) |
| 123 | + |
| 124 | + return ( |
| 125 | + <div className="p-2"> |
| 126 | + <h3>Full-Width Column Resizing</h3> |
| 127 | + <p> |
| 128 | + The table fills its container. The last column stretches to fill any |
| 129 | + remaining space. Try resizing individual columns — the last column |
| 130 | + adjusts automatically. Resize the browser window to see the table adapt. |
| 131 | + </p> |
| 132 | + <div className="h-4" /> |
| 133 | + <div ref={tableContainerRef} className="table-container"> |
| 134 | + <div |
| 135 | + className="divTable" |
| 136 | + style={{ |
| 137 | + ...columnSizeVars, |
| 138 | + width: tableWidth, |
| 139 | + }} |
| 140 | + > |
| 141 | + <div className="thead" style={{ position: 'sticky', top: 0 }}> |
| 142 | + {table.getHeaderGroups().map((headerGroup) => ( |
| 143 | + <div key={headerGroup.id} className="tr"> |
| 144 | + {headerGroup.headers.map((header) => ( |
| 145 | + <div |
| 146 | + key={header.id} |
| 147 | + className="th" |
| 148 | + style={{ |
| 149 | + width: `calc(var(--header-${header.id}-size) * 1px)`, |
| 150 | + }} |
| 151 | + > |
| 152 | + {header.isPlaceholder ? null : ( |
| 153 | + <table.FlexRender header={header} /> |
| 154 | + )} |
| 155 | + <div |
| 156 | + onDoubleClick={() => header.column.resetSize()} |
| 157 | + onMouseDown={header.getResizeHandler()} |
| 158 | + onTouchStart={header.getResizeHandler()} |
| 159 | + className={`resizer ${ |
| 160 | + header.column.getIsResizing() ? 'isResizing' : '' |
| 161 | + }`} |
| 162 | + /> |
| 163 | + </div> |
| 164 | + ))} |
| 165 | + </div> |
| 166 | + ))} |
| 167 | + </div> |
| 168 | + <div className="tbody"> |
| 169 | + {table.getRowModel().rows.map((row) => ( |
| 170 | + <div key={row.id} className="tr"> |
| 171 | + {row.getAllCells().map((cell) => ( |
| 172 | + <div |
| 173 | + key={cell.id} |
| 174 | + className="td" |
| 175 | + style={{ |
| 176 | + width: `calc(var(--col-${cell.column.id}-size) * 1px)`, |
| 177 | + }} |
| 178 | + > |
| 179 | + {cell.renderValue<string>()} |
| 180 | + </div> |
| 181 | + ))} |
| 182 | + </div> |
| 183 | + ))} |
| 184 | + </div> |
| 185 | + </div> |
| 186 | + </div> |
| 187 | + <div className="h-4" /> |
| 188 | + <pre style={{ fontSize: '12px' }}> |
| 189 | + {JSON.stringify( |
| 190 | + { |
| 191 | + containerWidth, |
| 192 | + totalColumnsWidth, |
| 193 | + shouldExtendLastColumn, |
| 194 | + columnSizing: table.state.columnSizing, |
| 195 | + }, |
| 196 | + null, |
| 197 | + 2, |
| 198 | + )} |
| 199 | + </pre> |
| 200 | + </div> |
| 201 | + ) |
| 202 | +} |
| 203 | + |
| 204 | +const rootElement = document.getElementById('root') |
| 205 | +if (!rootElement) throw new Error('Failed to find the root element') |
| 206 | + |
| 207 | +ReactDOM.createRoot(rootElement).render( |
| 208 | + <React.StrictMode> |
| 209 | + <App /> |
| 210 | + </React.StrictMode>, |
| 211 | +) |
0 commit comments