Blog>
Snippets

Making TanStack Table Responsive

Showcase the steps to ensure a TanStack Table's layout and content adjust seamlessly across various screen sizes.
import { useReactTable, getCoreRowModel } from '@tanstack/react-table';
import { useMemo, useState, useEffect } from 'react';
First, we import necessary hooks from TanStack Table and React. 'useReactTable' is used to manage the table state and logic, while 'useState' and 'useEffect' are for managing component state and lifecycle.
const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
});
We initialize the table instance using 'useReactTable' hook. We pass our data and column configurations, along with the core row model enhancer.
const [windowWidth, setWindowWidth] = useState(window.innerWidth);

useEffect(() => {
  function handleResize() {
    setWindowWidth(window.innerWidth);
  }
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);
We use a state to track the window width and a side effect to update this state whenever the window is resized. This allows us to dynamically adjust the table layout based on the screen size.
const mobileBreakpoint = 768; // Define your mobile breakpoint

const dynamicColumns = useMemo(() => columns.map(column => ({
  ...column,
  size: windowWidth < mobileBreakpoint ? window.innerWidth / 2 : column.size,
})), [windowWidth]);
Here we calculate if the current window width is below our defined mobile breakpoint. If it is, we adjust the column sizes to ensure the table content fits well on smaller screens. We use 'useMemo' to only recalculate when 'windowWidth' changes.
const mobileTable = useReactTable({
  data,
  columns: dynamicColumns,
  getCoreRowModel: getCoreRowModel(),
});
Finally, we initialize a new table instance for mobile, using our dynamically adjusted columns. This ensures our table's layout and content adapt well to both desktop and mobile screens.