MUI v5 + styled() + ListItemButton: property 'to'/'component' does not exist

Viewed 1057

In the migration from MUI v4 to v5 I'm hitting this road block: in v4 I've used makeStyles(), but now want to fully migrate to styled(): I can't get Typescript to accept a styled(ListItemButton)(...) with to= and component= properties.

I've seen and read MUI's guide on Wrapping components which actually made things even less clear to me; admittedly, I'm neither a Typescript nor MUI wizard. My confusion is fueled by the guide's examples being incomplete, such as obviously lacking some non-obviously imports which seem to need imported symbol renaming, so automatic completion won't work or turn up multiple candidates.

This is a minimized example triggering the Typescript error, see below for codesandbox link.

import React from "react"
import {
  Avatar,
  Link,
  ListItemAvatar,
  ListItemButton,
  styled
} from "@mui/material"

const ListItemButtonLink = styled(ListItemButton)(({ theme }) => ({
  // ...here be styling
}))

interface LinkedListItemProps {
  path: string
}

export const LinkedListItem = ({ path }: LinkedListItemProps) => {
  return (
    <ListItemButtonLink key={42} dense to={path} component={Link}>
      <ListItemAvatar>
        <Avatar>A</Avatar>
      </ListItemAvatar>
      Here Be Item
    </ListItemButtonLink>
  )
}

I'm totally out in the dark in how to get this working, as the Guide example doesn't pass Typescript checking either.

Looking through the MUI issues I found an issue that tackled the Guide issue, but doesn't really seem to fix it in a way that I could use.

I've also seen and read MUI button with styled-components including react router Link, but the solution is basically the non-Typescript guide version of a kind.

Edit styled-listitembutton (updated)

1 Answers

You're using Link from the MUI package, this Link is just an anchor element but with better style integration with MUI theme, The Link you might want to use is from react-router which has a to prop, so change your code to:

import { Link } from "react-router-dom";

If you use styled and want the resulted component to have the prop to from react-router, you can add the generic type parameter to the HOC:

import { Link, LinkProps } from "react-router-dom";

const ListItemButtonLink = styled(ListItemButton)<LinkProps>(({ theme }) => ({
  // ...here be styling
}));

Codesandbox Demo

Related