Search code examples
reactjstypescriptmaterial-uistyled-components

MUI styled component and TypeScript


I have the following codes

import {Button,ButtonProps} from '@mui/material';
import { alpha, styled } from '@mui/material/styles';
import { Link as RouterLink } from 'react-router-dom';

const BackButton = styled(Button)<ButtonProps>(({ theme }) => ({
  borderColor: alpha(theme.palette.text.primary, 0.5),
  padding: theme.spacing(1),
}));

and

  const backButton = (
    <BackButton
      to={'/my/path'}
      component={RouterLink}
      fullWidth
      variant="outlined"
      color="inherit"
    >
      Back
    </BackButton>
  );

I have a typescript error for to props, How can I fix it?

TS2322: Type '{ children: string; to: string; component: typeof Link; fullWidth: true; variant: "outlined"; color: "inherit"; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses>; color?: "inherit" | "error" | "primary" | "secondary" | "success" | "info" | "warning"; ... 9 more ...; variant?: "text" | ... 1 more ... | "contained"; } & ... 4 more ... & { ...; }'.   Property 'to' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses>; color?: "inherit" | "error" | "primary" | "secondary" | "success" | "info" | "warning"; ... 9 more ...; variant?: "text" | ... 1 more ... | "contained"; } & ... 4 more ... & { ...; }'.

Solution

  • See the components complications section on the MUI Typescript page.

    Modify your styled component to add a type conversion at the end:

    const BackButton = styled(Button)(({ theme }) => ({
      borderColor: alpha(theme.palette.text.primary, 0.5),
      padding: theme.spacing(1),
    })) as typeof Button;