'How to enable ListItemButton to use React Router v6 Link?

I'm trying to follow the example given in the MUI's do of Mini variant drawer to make the left ListItemButton to work with React Router v6's Link element. The documentation wasn't very clear on how to achieve that with a router library. I tried several variations but could not get it to work. The CodeSandBox link from MUI is here. Can someone please show me how to enable the ListItemButton to work with a path like /my-path?



Solution 1:[1]

Import the Link component from react-router-dom and pass as the component of the ListItemButton.

props

Name Type Default Description
component elementType The component used for the root node. Either a string to use a HTML element or a component.
import { Link } from 'react-router-dom';

...

<List>
  {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
    <ListItemButton
      key={text}
      component={Link} // <-- pass Link as component
      to={... pass a target path ...}
      sx={{
        minHeight: 48,
        justifyContent: open ? 'initial' : 'center',
        px: 2.5,
      }}
    >
      <ListItemIcon
        sx={{
          minWidth: 0,
          mr: open ? 3 : 'auto',
          justifyContent: 'center',
        }}
      >
        {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
      </ListItemIcon>
      <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />
    </ListItemButton>
  ))}
</List>

Edit how-to-enable-listitembutton-to-use-react-router-v6-link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1