next.jsmaterial-uimenuitemappbar

MUI MenuItem NextJS Link : Error while using those components


I got an issue trying to use MUI MenuItem and NEXTJS13 Link. Versions: MUi: "@mui/material": "^5.13.5", NEXTJS: "next": "13.4.5",

import MenuItem from "@mui/material/MenuItem"; import { Link } from "next/link";

https://mui.com/material-ui/react-app-bar/

I've tried: A)

<Link href={`/main`}>
  <a>
    <MenuItem key={1}>lorem</MenuItem>
  </a>
</Link>

Error showed: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'muiSkipListHighlight')

B)

<MenuItem key={1}>
 <Link href={`/main`}>
   lorem
 </Link>
</MenuItem>

Error showed: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of ResponsiveAppBar. (ResponsiveAppBar is the component I'm creating)

C)

function ALink() {
    return <Link href="/">lorem</Link>;
}

. . .

<MenuItem key={1} component={ALink()>
</MenuItem>

Error showed: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of MuiButtonBaseRoot.

D) Just not know what to try, I added a insie Link:

<MenuItem key={1}>
 <Link href={`/main`}>
   <a>lorem</a>
 </Link>
</MenuItem>

Error showed: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

If I quit the Link, it works correctly. But it's not what expected.

<MenuItem key={1}>
  {/* <Link href={`/main`}>asd</Link> */}
  lorem
</MenuItem>

Thanks,

EDIT: I've answer this with a workaround, but when I need to use a Link to scroll in the same page, I got this problem. (The answer isn't market as correct because of this)


Solution

  • Out of the box solution. Instead of using link, I used a button and then onclick function for this issue. When the MenuItem has the param of pageScroll = true, then it will be calling the fucntion onBtnClickDirect (and the url passed as param too).

     function move(url, pageScroll = null) {
        if (pageScroll !== true) {
          router.push(url);
        } else {
          onBtnClickDirect(url);
        }
      }
    

    The other used functions:

    const onBtnClickDirect = (goToRef) => {
      const goto = goToRef;
      setTimeout(() => {
        scroll2El(goto);
      }, 100);
    };
    const scroll2El = (elID) => {
      window.scrollTo({
        top: document.getElementById(elID).offsetTop,
        behavior: "smooth",
      });
    };
    

    So, up to now you can get two options for the same issue.

    I hope it helps someone.