score:9

Accepted answer

Material UI custom theme V5

Material UI custom theme in React with Typescript v4->v5 migration guide. create separate file for declaration.

👉 theme.d.ts

import { Theme, ThemeOptions } from '@mui/material/styles';

declare module '@mui/material/styles' {
  interface CustomTheme extends Theme {
    status: {
      danger: string;
    };
  }
  // allow configuration using `createTheme`
  interface CustomThemeOptions extends ThemeOptions {
    status?: {
      danger?: string;
    };
  }
  export function createTheme(options?: CustomThemeOptions): CustomTheme;
}

it will override default createTheme function with custome theme configuration. now you can use custom config in theme as mention below 👇.

👉 theme.ts

import { createTheme } from '@mui/material/styles';
import { orange, red } from '@mui/material/colors';

const theme = createTheme({
  status: {
    danger: red[500],
  },
  palette: {
    primary: {
      main: orange[500],
    },
  },
});

export default theme;

score:2

Amir's answer wasn't working for me, i didn't have the types while using styled components, so what ended up working for me is to use the same names for the new interfaces and renaming the ones that came from mui

import { Theme as MUITheme, ThemeOptions as MUIThemeOptions } from '@mui/material/styles';

declare module '@mui/material/styles' {
  interface Theme extends MUITheme {
    accent: {
      main: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions extends MUIThemeOptions {
    accent?: {
      main?: string;
    };
  }
  export function createTheme(options?: ThemeOptions): Theme;
}

score:6

What @kasperoo writes but instead make it more generic since typing styles is way to much work:

// imported theme from separate file
import { themeDetails } from './utils/theme';

declare module '@material-ui/core/styles/createMuiTheme' {
        interface ThemeOptions {
          [key: string]: any; // 
        }
    }
const theme = createMuiTheme({ themeDetails, 'theme name' });

score:22

Material-UI has got typing declarations already defined so you can't just add extra properties to it. You would have to extend the interface via module augmentation:

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

declare module '@material-ui/core/styles/createMuiTheme' {
    interface ThemeOptions {    
        themeName?: string  // optional
    }
}

const palette = {
  primary: { main: '#3f51b5' },
  secondary: { main: '#f50057' }
};

const themeName = 'San Marino Razzmatazz Sugar Gliders';

export default createMuiTheme({ palette, themeName });

Related Query

More Query from same tag