0

This is my theme config in my MUI app:

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

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

export const theme = createTheme({
  cssVariables: {
    cssVarPrefix: 'abc',
    colorSchemeSelector: 'class',
  },
  colorSchemes: {
    dark: true,
  },
});

How can I have different values for myVariable for the dark and light mode?

So in dark mode, the value might be 'a' and in light mode 'b' - the values should switch automatically when I change modes, like any other CSS variable.

I am using MUI 7.3.5.

2 Answers 2

2

You can create these three files, starting with the index that also defines the types:

themeTypes.ts

export interface CustomPaletteExtensions {
    customVariable: string;
}

declare module '@mui/material/styles' {
    interface Palette extends CustomPaletteExtensions {}
    interface PaletteOptions extends Partial<CustomPaletteExtensions> {}
}

Then a file for dark and another one for light, for example:

import { createTheme } from '@mui/material/styles';
import './themeTypes';

const lightTheme = createTheme({
    palette: {
        mode: 'light',
        customVariable: '#fff'
    }
}
export default lightTheme;

and to apply them use it in the ThemeProvider:

<ThemeProvider theme={theme}>
    {children}
</ThemeProvider>

"theme" is here a import from lightTheme or darkTheme

You can use like

styles={{ color: "customVariable" }}
Sign up to request clarification or add additional context in comments.

Comments

1

The final version I went with is a little different from the provided answer, but the decisive hint was to do the module augmentation with the Palette object:

export interface CustomPaletteExtensions {
  customBackground: string;
}

declare module '@mui/material/styles' {
  interface Palette extends CustomPaletteExtensions {}

  interface PaletteOptions extends Partial<CustomPaletteExtensions> {}
}

const theme = createTheme({
  cssVariables: {
    cssVarPrefix: 'abc',
    colorSchemeSelector: 'class',
  },
  colorSchemes: {
    dark: {
      palette: {
        customBackground: '#2e2f3b',
      },
    },
    light: {
      palette: {
        customBackground: '#ffffff',
      },
    },
  },
});

export const theme;

Now I can use it like this:

var(--abc-palette-customBackground)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.