React / Material-UI: Use variable reference in custom theme

Viewed 914

Is there a way in Material-UI (React) to use a reference in a custom theme to a variable defined in the same theme? For example, the component MuiBottomNavigation should use the primary color (main) as background.

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

const theme = createTheme({
    palette: {
        primary: {
            main: '#f6b1b2'
        }
    },
    components: {
        MuiBottomNavigation: {
            styleOverrides: {
                root: {
                    // This is not working
                    backgroundColor: {palette.primary.main}
                },
            }
        }
    }
});
2 Answers

You can achieve this by creating several themes and then merging them into one:

// Define all your default styles
const themeBase = createTheme({
  palette: {
    primary: {
      main: "#f6b1b2"
    }
  }
});

// Define all your component styles
const themeComponents = createTheme({
  components: {
    MuiBottomNavigation: {
      styleOverrides: {
        root: {
          backgroundColor: themeBase.palette.primary.main
        },
      }
    }
  }
});

const theme = createTheme({
  ...themeBase,
  components: themeComponents.components,
});

Of course, you wouldn't need to create an extra theme for the components. You could also just insert them into the final theme.

No, you can't. there is no such API to access the theme when you define it. So something like this wouldn't work

styleOverrides: {
  root: {
    backgroundColor: theme => theme.palette.primary.main
  },
}

To workaround this you can put the commonly shared value into a variable and reference it:

const primaryMain = '#f6b1b2';

const theme = createTheme({
  palette: {
    primary: {
      main: primaryMain,
    }
  },
  components: {
    MuiBottomNavigation: {
      styleOverrides: {
        root: {
          backgroundColor: primaryMain,
        }
      }
    }
  }
});

If you only need to access a default theme variable, you can create one and reference it like this:

const defaultTheme = createTheme();

const theme = createTheme({
  components: {
    MuiBottomNavigation: {
      styleOverrides: {
        root: {
          backgroundColor: defaultTheme.palette.primary.main,
        }
      }
    }
  }
});
Related