How to use Material UI custom theme in React with Typescript
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 });
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;
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' });