Typescript/React/MUI use custom color on Button component

Viewed 259

I trying to apply custom color to Button component but I getting error. What is possible solution for that?

I made module module augmentation like in docs but problem still remain:

https://mui.com/material-ui/customization/palette/#adding-new-colors

Message: Button.d.ts(34, 5): The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & { component: ElementType<any>; } & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; ... 10 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...>'

const theme = createTheme({
  palette: {
    primary: {
      main: '#ff0000',
    },
    play: {
      main: '#ffffff',
      contrastText: 'black'
    },
    moreInfo: {
      main: '#6c6c6e',
      contrastText: 'white'
    },
    tonalOffset: 0.2,
  },
  breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 900,
      lg: 1200,
      xl: 1536,
    },
  },
});
import { createTheme } from '@mui/material/styles'

declare module '@mui/material/styles' {
    interface Palette {
        play?: Palette['primary'];
        moreInfo?: Palette['primary'];
    }
    interface PaletteOptions {
        play?: PaletteOptions['primary'];
        moreInfo?: PaletteOptions['primary'];
    }
  }

enter image description here

1 Answers

The problem is that adding colors to the palette in MUI (even when you augment the createPalette module as you have here) does not automatically add them to the Button's available colors. In order to allow the Button's Color prop, you also need to extend an additional interface:

declare module '@mui/material' {
    interface ButtonPropsColorOverrides {
        play,
        moreInfo,
    }
}

You will need to do this on a per-component basis. I've also extended createPalette in a slightly different way, but yours may also be correct:

import "@mui/material/styles/createPalette";
declare module '@mui/material/styles/createPalette' {
    interface PaletteOptions {
        play?: PaletteColorOptions,
        moreInfo?: PaletteColorOptions,
    }

    interface Palette {
        play: PaletteColor,
        moreInfo: PaletteColor,
    }
}
Related