DEV Community

Discussion on: Using Next.js Link Component with Material UI Buttons and Menu Items

Collapse
 
codingjlu profile image
codingjlu

Sure. I found this working for me and wanted to share it with anyone who'd think it's useful. In link.js:

import NextLink from "next/link";
import MuiLink from "@mui/material/Link";
import MuiButton from "@mui/material/Button";

export default function Link({ type, href, children, ...props }) {
  if (type === "link" || !type) {
    return (
      <NextLink href={href} passHref>
        <MuiLink {...props}>{children}</MuiLink>
      </NextLink>
    );
  } else if (type === "button") {
    return (
      <NextLink href={href} passHref>
        <MuiButton {...props}>{children}</MuiButton>
      </NextLink>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Then you can just use it as a utility components just like you would with Next and MUI's buttons:

import Link from "../path/to/link";
// Later...
<Link type="button" href="/somewhere">Yay!</Link>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
cristianeto profile image
Cristian Guamán

super!!!

Thread Thread
 
petroswursta profile image
petros-wursta

I tried this but was not able to get it to work.

I added a links.js file and added your code.

then this
import Link from "../path/to/link";
// Later...
Yay!

but it doesn't work, I get the following error.

Any help please?!

Image description

Thread Thread
 
codingjlu profile image
codingjlu

Could you show a bit more code? Did you adjust the code to actually fit your project? Did you paste the correct code into your link component?

Thread Thread
 
petroswursta profile image
petros-wursta

Thank you! Looks like I got it to work. I needed to install the mui library.

I just need to add styling b/c it just shows up as texts instead of a button.

Thread Thread
 
codingjlu profile image
codingjlu

Great, glad it worked out!