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
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}
/>
);
};