Reputation: 85
I have created a reusable table component using react-table v8 by tanstack. Im now trying to implement react-virtual by tanstack to this reusable table. Im using "@tanstack/react-virtual": "^3.0.0-beta.54" and "@tanstack/react-table": "^8.9.2". Im not finding any example online with the integration of the lates versions of this two libraries. Can somebody help me with this?
import type { ReactElement } from "react";
import { useRef } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeaderCell,
TableRow,
} from "./style";
import {
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import type { ColumnDef } from "@tanstack/react-table";
import { useVirtualizer } from "@tanstack/react-virtual";
interface TableProps {
columns: Array<ColumnDef<any, string>>;
data: any;
}
function CustomTable(props: TableProps): ReactElement {
const { columns, data } = props;
const parentRef = useRef<HTMLTableElement>(null);
const tableInstance = useReactTable({
columns,
data,
getCoreRowModel: getCoreRowModel(),
});
const rowVirtualizer = useVirtualizer({
count: tableInstance.getRowModel().rows.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 15,
});
return (
<div ref={parentRef}>
<Table>
<TableHead>
{tableInstance.getHeaderGroups().map(headerGroup => {
return (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map(header => {
return (
<TableHeaderCell key={header.id}>
<span>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</span>
</TableHeaderCell>
);
})}
</TableRow>
);
})}
</TableHead>
<TableBody>
{tableInstance.getRowModel().rows.map(row => {
return (
<TableRow $border key={row.id}>
{row.getVisibleCells().map(cell => {
return (
<TableCell key={cell.id}>
<span>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</span>
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
</Table>
</div>
);
}
export default CustomTable;
Upvotes: 5
Views: 554