material-ui tabs with nextjs?

Viewed 4447

I have a project in material-ui, nextjs and typescript. I'm trying to get my navbar to work with nextjs:

import * as React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Link from "next/link";
import {Tab, Tabs} from "@material-ui/core";

export default function NavBar() {
  return (
        <AppBar position="static">
          <Tabs>
              <Tab label="Timer"><Link href="timer" /> </Tab>
              <Tab label="Home" to="/" component={Link}  />
          </Tabs>
        </AppBar>
  );
}

But it causes the build to fail. Is there something I'm missing?

4 Answers

In this case, I believe you want to wrap the <Tab /> elements with the <Link /> ones.

<Tabs>
    <Link href="/timer" passHref>
      <Tab label="Timer" />
    </Link>
    <Link href="/" passHref>
      <Tab label="Home" />
    </Link>
</Tabs>

This might be better for SEO:

<Link href="/timer" passHref>
  <Tab component="a" label="Timer" />
</Link>

Reason is because Link doesn't add href to the child (even if it's an a component). passHref forces this, but preventDefault can't be put onClick as mentioned in the MUI docs as it won't change the URL.

Other solutions basically wrap the Next.js' Link around MUI's Tab. It probably breaks the compatibility between Tabs and Tab.

Why not style Link to fill the entire Tab? Code for MUI v5:

<Tab
  onClick={(event) => {
    event.preventDefault()
  }}
  label={
    <Link href={opt['href']} passHref>
      <Typography
        component="a"
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0
        }}
      >
        {opt['label']}
      </Typography>
    </Link>
  }
  value={opt['value']}
/>

Here is an example straight from MUI v.5.

https://codesandbox.io/s/d2dco?file=/demo.tsx

Create LinkTab component:

import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';

interface LinkTabProps {
  label?: string;
  href?: string;
}

function LinkTab(props: LinkTabProps) {
  return (
    <Tab
      component="a"
      onClick={(event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
        event.preventDefault();
      }}
      {...props}
    />
  );
}

Usage:

   <LinkTab label="register" href="/register" />
   <LinkTab label="login" href="/login" />

But to be honest <Tab label="login" href="/login" /> just works for me

Related