How can I extend Color Palette in Material UI with Typescript

Viewed 8891

I am new on react and typescript. I am trying to extend the color palette on a global theme.

in my themeConitainer.tsx

import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme';

declare module '@material-ui/core/styles/createPalette' {
  // allow configuration using `createMuiTheme`
  interface Palette {
    accent: PaletteColor
  }
  interface PaletteOptions {
    accent: PaletteColorOptions,
    tertiary: PaletteColorOptions
  }
};

const ThemeContainer: React.FunctionComponent<Props> = (props, themeOptions: ThemeOptions) => {
  const { children } = props;

  const theme = useMemo(() => {
    const nextTheme = createMuiTheme({
      ...themeOptions,
      palette: {
        accent: {
          main: '#ff0000'
        },
      }
    });

    return nextTheme;
  });

  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};

export default ThemeContainer;


but on my component, there was an error.

enter image description here

No overload on this call.

Thank you in advance.

3 Answers

For those arriving here using MUI 5, you can overwrite the Palette and PaletteOptions with your custom types, then just extend those interfaces with the existing types:

declare module '@mui/material/styles/createPalette' {
  interface Palette {
    neutralShade: {main: string};
  }

  interface PaletteOptions {
    neutralShade?: {main: string};
  }
}

The short answer is that you can't (and you shouldn't) do this.

The long answer contains the following explanation:

Material UI is (one of) React's implementations of the Material Design concept.

Material Design is a design language that Google developed in 2014. Expanding on the "card" motifs that debuted in Google Now, Material Design uses more grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows.

As part of Material Design you have the color system, which contains a primary/secondary (and a variant for each of them).
You also have the dark/light theme which you can control, and each of them also have primary/secondary colors.

If you need more colors - you probably don't follow the idea of Material Design.

You can always use CSS/Variables/Styled components for extra design options, but in general you shouldn't.

Related