Blog>
Snippets

Dynamically Adjusting Column Width Based on Viewport Size

Show a function that listens to viewport changes and dynamically adjusts the TanStack table's column widths using state management.
import React, { useState, useEffect } from 'react';
import { useReactTable } from '@tanstack/react-table';
Import necessary hooks from React and the useReactTable hook from @tanstack/react-table.
const [columnWidths, setColumnWidths] = useState({ title: 200, category: 150, description: 300 });
Initialize state to store custom column widths.
useEffect(() => {
    const handleResize = () => {
        const viewportWidth = window.innerWidth;
        setColumnWidths({
            title: viewportWidth * 0.2,
            category: viewportWidth * 0.15,
            description: viewportWidth * 0.35
        });
    };
    window.addEventListener('resize', handleResize);
    handleResize(); // Call on mount to set initial sizes
    return () => window.removeEventListener('resize', handleResize);
}, []);
Add an effect that updates column widths based on the viewport size. This effect adds and cleans up an event listener for window resize events.
const columns = React.useMemo(() => [
    {
        accessorKey: 'title',
        header: 'Title',
        size: columnWidths.title
    },
    {
        accessorKey: 'category',
        header: 'Category',
        size: columnWidths.category
    },
    {
        accessorKey: 'description',
        header: 'Description',
        size: columnWidths.description
    }
], [columnWidths]);
Define the table columns using React.useMemo to ensure they're only recalculated when columnWidths change. Each column's size is dynamically set based on the current state.
const data = React.useMemo(() => [...], []); // Replace [...] with your data
Define the data for the table. Replace [...] with your actual data array.
const tableInstance = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
});
Initialize the table instance with useReactTable, passing in data and the dynamically adjusted columns.
return (
    <table>
        {/* Render your table using tableInstance */}
    </table>
);
Render the table. Use the tableInstance generated with useReactTable to build your table structure.