Blog>
Snippets

Conditional Column Rendering Based on Screen Size

Provide a code snippet that conditionally renders columns in a TanStack table based on the current screen size, enhancing both performance and user experience.
const useMediaQuery = (query) => {
  const [matches, setMatches] = React.useState(false);
  React.useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    media.addEventListener('change', listener);
    return () => media.removeEventListener('change', listener);
  }, [matches, query]);
  return matches;
};
Defines a custom hook that listens to changes in the screen size, matching a specific media query.
const columns = React.useMemo(() => {
  // Check if screen width is less than 768 pixels
  const isMobile = useMediaQuery('(max-width: 768px)');

  const baseColumns = [
    { header: 'Name', accessorKey: 'name' },
    { header: 'Category', accessorKey: 'category' },
    { header: 'Description', accessorKey: 'description' }
  ];

  // Optionally, add or remove columns based on screen size
  if (isMobile) {
    return baseColumns.filter(column => column.accessorKey !== 'description');
  }
  return baseColumns;
}, []);
Uses the custom hook to conditionally modify the column definitions based on the screen size. Removes the 'Description' column on screens narrower than 768 pixels.