Búsqueda de sitios web

reactjs - Material UI 5.0 Typescript React Tema personalizado


Tengo un problema con la personalización de un tema en Material UI 5.0 usando TypeScript.

tema.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;

Pero cuando intento usarlo, no funciona

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

Se muestra como any o tengo este error de TypeScript:

¿Quisiste decir 'typeof CustomTheme'?

Mi pregunta es cuál es la manera correcta de implementar un tema personalizado con Material UI 5.0 y 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",

Respuesta #1

En Material v5 puedes sobrescribir el estilo predeterminado usando styleOverrides

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

y este estilo se aplicará a cada Button

Enlace de referencia: https://mui.com/customization/theme-components/#global-style-overrides

Artículos relacionados