Search code examples
javascriptreactjstypescriptmaterial-uicreate-react-app

How to use Material UI custom theme in React with Typescript


Using this tool https://react-theming.github.io/create-mui-theme/ I get a js file and a json file as mentioned on above theme generator page in respective paths as mentioned:

// src/ui/theme/index.js
/* src/ui/theme/theme.json */

Now they work fine when I leave the file extension to js. As soon as I try to use js as a tsx file the editor starts complaining. I have all the necessary setup done via CRA Typescript in tsconfig file also. Also necessary config from this page https://material-ui.com/guides/typescript/

When I try this it does not work, any ideas if I am missing something?

// My amended index.tsx file

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

const palette = {
  primary: { main: '#3f51b5' },
  secondary: { main: '#f50057' }
};
const themeName = 'San Marino Razzmatazz Sugar Gliders';

export default createMuiTheme({ palette, themeName });

Also the theme.json is untouched by me. I am still learning sorry, any ideas if this is an interface problem and how to use it?


Solution

  • 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;