Home > Software design >  How to type a button with react-router-dom Link in MUI v5
How to type a button with react-router-dom Link in MUI v5

Time:10-04

Problem

I am migrating from MUI v4 to v5 and I am having an issue using the styled function to style a Button component. For some reason, when I use MyButton instead of Button, the compiler has an issue with the component prop.

Error Message

Type '{ children: string; component: <S = unknown>(props: LinkProps<S> & RefAttributes<HTMLAnchorElement>) => ReactElement<any, string | JSXElementConstructor<any>> | null; to: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & ... 5 more ... & { ...; }'.
  Property 'component' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | ... 5 more ... | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & ... 5 more ... & { ...; }'.

My Code

import { alpha, Button, styled } from "@mui/material";
import React from "react";
import { Link, HashRouter as Router } from 'react-router-dom';
import "./styles.css";

export default function App() {

  const MyButton = styled(Button)(({ theme }) => ({
    color: 'white',
    margin: theme.spacing(1),
    backgroundColor: alpha(theme.palette.common.white, 0.25),
    '&:hover': {
      backgroundColor: alpha(theme.palette.common.white, 0.35),
    },
  }));

  return (
    <Router basename="/">
      <div className="App">
        <MyButton component={Link} to="/"> // why doesn't this work?
          My Button
        </MyButton>
      </div>
    </Router>
  );
}

CodeSandBox

Codesandbox Demo

  • Related