Blog>
Snippets

Using Media Queries in TanStack Table for Responsive Design

Illustrate how to apply CSS media queries directly to TanStack table columns to change their widths based on different screen sizes.
const columnHelper = createColumnHelper();

const columns = [
  columnHelper.accessor('name', {
    // Default size
    size: 100,
    header: 'Name',
    cell: info => info.getValue(),
    // Using a function to dynamically adjust size based on window width
    getSize: () => window.innerWidth < 768 ? 50 : 100, // Smaller size on small screens
  }),
  // Repeat for other columns as needed
];
Defines a column for a TanStack table using the columnHelper. The 'getSize' property function dynamically sets the column's size based on the browser window's inner width, making the column responsive without relying on CSS media queries.
function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}
Defines a custom React hook that listens to window resize events and provides the current window size as a state. This hook can be used to re-render components that need to be responsive.
const [width] = useWindowSize();

const responsiveColumns = columns.map(col => ({
  ...col,
  size: col.getSize ? col.getSize(width) : col.size,
}));
Maps through the defined columns, checking if each has a 'getSize' function. If so, it invokes this function with the current window width (provided by 'useWindowSize' hook) to determine the column's size. This updates column sizes on window resize.