Sergiu Tonț
Sergiu Tonț

Reputation: 185

Material UI Custom theme color assign Typescript

I created my own custom theme and I'm trying to assing one of the colors I created to a button, but when I'm trying to set it as:

color={theme.pallete.lightGrey}

I'm getting this error:

No overload matches this call
Overload 1 of 3, '(props: { href: string; } & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | "secondary" | "success" | "error" | "info" | "warning" | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & Pick<...> & CommonProps & Pick<...>): Element', gave the following error.

Does this means that you can't assign custom colors to the color attribute? Only through styling

Upvotes: 2

Views: 1995

Answers (1)

Ice_mank
Ice_mank

Reputation: 430

If you are using typescript use the global theme approach in this case,

  1. I have 2 custom colours which are neutral and backgroundSecondary so you need to register the types in material UI types
    declare module "@mui/material/styles" {
      interface CustomPalette {
        neutral: {
          main: string;
          contrastText: string;
        };
        backgroundSecondary: string;
      }
      interface Palette extends CustomPalette {}
      interface PaletteOptions extends CustomPalette {}
    }
  1. Then register that button show be able to read the custom colors
    In my case I only need neutral to be read by the Button component so you do this
declare module "@mui/material/Button" {
  interface ButtonPropsColorOverrides {
    neutral: true;
  }
}
  1. You set up your theme (in most cases this would have already been setup)
let theme = createTheme({
  palette: {
    primary: {
      main: "some-color",
    },
    secondary: {
      main: "some-color",
    },
    error: {
      main: "some-color",
    },
    neutral: {
      main: "#fff",
      contrastText: "#002255",
    },
    backgroundSecondary: "#f8fafc",
  },
});

  1. Finally the usage
<Button variant="outlined" color="neutral"> Click Me</Button>

Upvotes: 4

Related Questions