How to use Next.js Link (next/link) component in a Material UI Menu?

Viewed 5269

I have a Material ui menu in the following way:

<Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={!!anchorEl} onClose={handleClose}>
    <MenuItem onClick={handleClose}>Profile</MenuItem>
    <MenuItem onClick={handleClose}>Log Out</MenuItem>
</Menu>

and want to use next.js Link tags with theMenuItem. What is the best way to do this?

I tried the following things:


The following doesn't render the <a> tag, but adds href to the <li> tag.

<Link href={'#'} passHref><MenuItem onClick={handleClose}>Log Out</MenuItem></Link>

I could add a prop to MenuItem to render <a> instead of <li> tag, however, since the menu is nested under <ul> tag, I'm not sure if having <ul><a>Log Out</a></ul> is a good idea


The following throws an error

<MenuItem onClick={handleClose} component={<Link href={'#'}>Log Out</Link>}></MenuItem>

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

6 Answers

As mentioned in the other answer giving the Link tag within the MenuItem tag will work as required and for the styling issues you have to give a textDecoration: 'none' and color: '#000' within the Link tag to avoid the underline and blue color of the Link text.

<MenuItem>
   <Link 
      style={{
          textDecoration: 'none', 
          color: '#000'
      }}
      href="#"
   >
    Log Out
   </Link>
</MenuItem>

This is what worked for me that also disables "the regular blue link with underline in the menu":

<MenuItem>
    <Link href="#">
        <a
            style={{
                textDecoration: 'none',
                color: '#000'
            }}
        >
            Profile
        </a>
    </Link>
</MenuItem>

You can put "Link" component inside the "MenuItem" component.

<MenuItem><Link href="#">Log Out</Link></MenuItem>

Add a tag inside link

<MenuItem onClick={handleClose} component={<Link href={'#'}><a>Log Out</a></Link>}></MenuItem>

See if the below code fix this, Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object:

const ALink = ({ url, linkText }) => <Link href={url}>
    <a>{ linkText }</a>
</Link>    
<MenuItem onClick={handleClose} component={ ALink({url: '#', linkText: 'Log Out') }></MenuItem>

Component prop inside <MenuItem> is The component used for the root node. Either a string to use a HTML element or a component. which defauts to <li> as material-ui official says.

If you want to keep <ul><li></li></ul> structure, you have to nest your <Link> component inside of <MenuItem> component.

So this may be what you wanted.

<MenuItem onClick={handleClose}>
  <Link href={'#'}>Log Out</Link>
</MenuItem>
Related