Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 936
Niner Avatar asked Dec 31 '25 05:12

Niner


1 Answers

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

like image 64
Drew Reese Avatar answered Jan 02 '26 02:01

Drew Reese