I badly need help about headlessUI tabs. I was trying to fix it my own and research but there's not enough resources about my problem. I still don't understand how this is not working, I also read the docs.
import { useEffect, useState } from "react";
import { Tab } from "@headlessui/react";
function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}
export default function Tabs({ tabs }) {
const [index, setIndex] = useState();
return (
<Tab.Group
defaultIndex={index}
onChange={(index) => {
console.log("Changed selected tab to:", index);
setIndex(index);
}}
>
<Tab.List className="text-xl space-x-9">
{tabs.map(({ tab }, index) => (
<Tab
key={index}
className={({ selected }) =>
classNames(
selected ? "text-gray-900" : "text-gray-400 font-avenir-roman"
)
}
>
{tab}
</Tab>
))}
</Tab.List>
<Tab.Panels>
{tabs.map(({ content }, index) => (
<Tab.Panel key={index}>{content}</Tab.Panel>
))}
</Tab.Panels>
</Tab.Group>
);
}
This is what I did to persist the currentTab
const [currentTab, setCurrentTab] = useState(0);
useEffect(() => {
localStorage.setItem("currentTab", JSON.stringify(currentTab));
}, [currentTab]);
useEffect(() => {
const currentTab = JSON.parse(localStorage.getItem("currentTab"));
if (currentTab) {
setCurrentTab(currentTab);
}
}, []);
<Tab.Group
defaultIndex={tab}
onChange={(currentTab) => {
setCurrentTab(currentTab);
router.replace(
{
pathname: `/path/userPath/edit/${id}`,
query: { tab: currentTab },
},
undefined,
{
shallow: true,
}
);
}}
>
UPDATE: You can also use the query.tab
to persist the tab.