Skip to content

Instantly share code, notes, and snippets.

@Mood-al
Last active May 15, 2022 00:45
Show Gist options
  • Save Mood-al/d3736a3efadb3b7e0b834b355983a3d6 to your computer and use it in GitHub Desktop.
Save Mood-al/d3736a3efadb3b7e0b834b355983a3d6 to your computer and use it in GitHub Desktop.
react tabs scrollable presist tab state on route changing in next js
const NavDemo = () => {
const [activeTab, setActiveTab] = React.useState(1);
const router = useRouter();
// get the id of the page and turn it into integer
const pageId = +router.asPath.split("/")[2];
React.useEffect(() => {
// if it equals 0 set the active tab to 0
if (pageId === 0) {
setActiveTab(0);
return;
}
// set the active tab state to the page id that we selected
setActiveTab(pageId || 1);
}, [pageId]);
// define a onClick function to bind the value on tab click
const onTabClick = (e, index) => {
setActiveTab(index);
};
return (
<>
<Tabs activeTab={activeTab} onTabClick={onTabClick}>
{/* generating an array to loop through it */}
{[...Array(20).keys()].map((item) => (
<Tab
key={item}
// change the router into the selected tab id
onClick={() =>
router.push(`/demos/${item}`, undefined, { scroll: false })
}
>
Page {item}
</Tab>
))}
</Tabs>
</>
);
};
export default NavDemo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment