Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript/React/MUI use custom color on Button component

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

like image 786
Telirw Avatar asked Jul 11 '26 23:07

Telirw


2 Answers

For MUI 5.11.14 i had to add true

declare module "@mui/material" {
  interface ButtonPropsColorOverrides {
    myCoolColour: true;
  }
}
like image 196
Thanasis Kapelonis Avatar answered Jul 14 '26 13:07

Thanasis Kapelonis


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,
    }
}
like image 28
Tim Hallowell Avatar answered Jul 14 '26 12:07

Tim Hallowell