25

Im trying to create a list of links in a sidebar. The problems is that if I use

<ListItem button component='a' href="/persons">

The page reloads instead of going to the url like a Link component would do.

<Link to='/persons' >

I wonder, how can I replace the Material UI listItem href behaviour with the react-router Link behaviour? This is the list im trying to fix:

// this breaks the design
<Link to='/persons' >
    <ListItem button>
        <ListItemIcon>
            <Icon>people</Icon>
        </ListItemIcon>
        <ListItemText primary="Personas" />
    </ListItem>
</Link>

// this reloads the page, i want to avoid
<ListItem button component='a' href="/persons">
    <ListItemIcon>
        <Icon>bar_chart</Icon>
    </ListItemIcon>
    <ListItemText primary="Reports" />
</ListItem>

This is how the link looks:

enter image description here

UselesssCat
  • 2,248
  • 4
  • 20
  • 35

2 Answers2

52

You can use Link as the component of the ListItem and use it as the following

<List>
  <ListItem component={Link} to="/reports">
    <ListItemIcon>
      <Icon>bar_chart</Icon>
    </ListItemIcon>
    <ListItemText primary="Reports" />
  </ListItem>
</List>
Rasuna Khatami
  • 1,021
  • 6
  • 4
6

For a <ListItem /> The component prop can be a string (for a dom element) or a react component itself.

https://material-ui.com/api/list-item/

You can define any component

const ListItemComponent  =  () => {
  return <Link to="/test">Check</Link>
}

as pass it as a component prop to <ListItem />.

        <List>
          <ListItem component={ListItemComponent}>
          </ListItem>
        </List>

Try this https://stackblitz.com/edit/react-ogpmxx

Nithin Thampi
  • 3,579
  • 1
  • 13
  • 13