How can I create an AppBar with Tabs as Link component?

Viewed 187

I would like to use Material-UI's Tabs and Tab components in my AppBar using Next.js and its Link component.

Very schematically, this is what I tried:

import AppBar from '@mui/material/AppBar';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import { useState } from 'react';

const Navbar = () => {
  const [selectedTab, setSelectedTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

  return (
    <AppBar position="static">
      <Tabs value={selectedTab} onChange={handleTabChange} indicatorColor="secondary">
        <Tab label="Album" />
        <Tab label="Profile" />
      </Tabs>
    </AppBar>
  )
}

The indicator (underlining) and active class works that way, but I'm struggling to use Next.js Link component while keeping those functioning.

I tried wrapping the Tab components with Link as suggested here, like this:

import AppBar from '@mui/material/AppBar';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Link from 'next/link';
import { useState } from 'react';

const Navbar = () => {
  const [selectedTab, setSelectedTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

  return (
    <AppBar position="static">
      <Tabs value={selectedTab} onChange={handleTabChange} indicatorColor="secondary">
        <Link href="/album" passHref>
          <Tab label="Album" />
        </Link>
        <Link href="/profile" passHref>
          <Tab label="Profile" />
        </Link>
      </Tabs>
    </AppBar>
  )
}

This works to redirect me but the indicator and the active class both stop working.

How can I use both the Link component from next.js while keeping all the active highlighting functionality of the Tabs component from MUI?

0 Answers
Related