Blog>
Snippets

Initial Setup for Virtual Scrolling with TanStack Table

Showcase the basic setup code to integrate virtual scrolling in a React TanStack Table, including the necessary imports and the initial configuration.
import { useTable, useBlockLayout, useScroll } from '@tanstack/table';
import { useMemo } from 'react';
Imports the necessary hooks from TanStack Table and useMemo from React.
const Table = ({ columns, data }) => {
  const defaultColumn = useMemo(() => ({
    width: 150 // Set a default width for each column
  }), []);
  
  const scrollOptions = useMemo(() => ({
    virtualizerOptions: {
      itemSize: 35 // Set a default row height
    }
  }), []);
  
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    
    // Get the virtualizer instance
    virtualRows,
    totalSize,
    scrollTo,
  } = useTable({
    columns,
    data,
    defaultColumn
  },
    useBlockLayout,
    useScroll(scrollOptions)
  );
  
  // Table rendering logic goes here
};
Sets up a Table component using useTable, useBlockLayout, and useScroll hooks for virtual scrolling.
// Usage example
// Define your columns and data outside of the component to avoid recreation on renders
const columns = [{ key: 'id', header: 'ID' }, { key: 'name', header: 'Name' }];
const data = [{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }];

// Render the Table component with the columns and data
<Table columns={columns} data={data} />;
Provides an example of how to use the Table component with predefined columns and data.