Tanstack React-table column hidden on mobile screeen

1k views Asked by At

I have a scenario, in which I have to hide some columns of react-table on a mobile screen. Note: I'm using Tanstack Table and Tailwind CSS for styling

2

There are 2 answers

0
Shubham Shinde On BEST ANSWER

Written custom hook for checking breakpoints and passing mobileColumns and desktopColumns conditionally:

useWindowSize.tsx

"use client";

import { useState, useEffect } from "react";

//a Util function that will conver the absolute width into breakpoints
function getBreakPoint(windowWidth: any) {
  if (windowWidth) {
    if (windowWidth < 480) {
      return "sm";
    } else if (windowWidth < 1024) {
      return "md";
    } else if (windowWidth < 1200) {
      return "lg";
    } else {
      return "xlg";
    }
  } else {
    return undefined;
  }
}

function useWindowSize() {
  const isWindowClient =
    typeof window === "object" && typeof window !== "undefined";
  const [windowSize, setWindowSize] = useState(
    isWindowClient
      ? getBreakPoint(window.innerWidth) //
      : undefined,
  );
  useEffect(() => {
    //a handler which will be called on change of the screen resize
    function setSize() {
      setWindowSize(getBreakPoint(window.innerWidth)); //
    }
    if (isWindowClient) {
      //register the window resize listener
      window.addEventListener("resize", setSize);
      //unregister the listerner on destroy of the hook
      return () => window.removeEventListener("resize", setSize);
    }
  }, [isWindowClient, setWindowSize]);
  return windowSize;
}

export default useWindowSize;

//Use

"use client";

import { DataTable } from "@/components/ui/data-table";
import useWindowSize from "@/hooks/useWindowSize";
import { useRouter } from "next/navigation";
import { desktopColumns, mobileColumns } from "./columns";

export const ContactsTable = ({ data }: any) => {
  const router = useRouter();
  const windowSize = typeof window !== "undefined" ? useWindowSize() : false;

  return (
      <DataTable
        searchKey="Fullname"
        columns={
          windowSize == "sm" || windowSize == "md" ? mobileColumns : desktopColumns
        }
        data={data}
      />
  );
};
0
Muhammad Asif On

I define columns separately for large screen and mobile screens, and pass columns to useReactTable hook such that

columns: window.innerWidth <= "1023"? columnsMobile: columns,

**

Is this a good approach or not?

**