6

I have problem with customization of a theme in Material UI 5.0 using typescript.

theme.ts

    import { createTheme } from '@mui/material';

declare module '@mui/material/styles' {
    interface Theme {
        custom: {
            buttonWidth: string;
        };
    }
    interface ThemeOptions {
        custom: {
            buttonWidth: string;
        };
    }
}

export const theme = createTheme({
    palette: {
        primary: {
            main: '#00F',
        },
    },
    typography: {
        body1: {
            fontFamily: 'Comic Sans',
        },
    },
    custom: {
        buttonWidth: '200px',
    },
});

export const CustomTheme= typeof theme;

But when I try to use it, it doesn't work

// CustomTheme imported
<Button sx={{ width: (theme: CustomTheme) => theme.custom.buttonWidth}} />

It's showed as any or I have this typescript error:

Did you mean 'typeof CustomTheme'?

My question is what is the right way to implement a custom theme with Material UI 5.0 and typescript

package.json

    // other dependencies
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@mui/icons-material": "^5.0.0",
    "@mui/material": "^5.0.0",
Spongi
  • 501
  • 3
  • 10
  • 19

1 Answers1

-3

In material v5 you can override the default style by using styleOverrides

const theme = createTheme({
  palette: {
    primary: {
      main: '#00F',
    },
  },
  typography: {
    body1: {
      fontFamily: 'Comic Sans',
    },
  },
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          width: 200,
        },
      },
    },
  },
})

and this style will be applied for every single Button

Reference link: https://mui.com/customization/theme-components/#global-style-overrides

Fred Nguyen
  • 285
  • 1
  • 3