简体   繁体   中英

Using theme palette colors in custom MUI button variant

I've got a MUI 5 button variant that I'd like to use existing theme palette colors on. I've got my appTheme.ts set up like this:

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

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    light: true;
  }
}

export const theme: Theme = createTheme({
  palette: {
    primary: {
      main: 'black',
      light: 'white',
    },
    secondary: {
      main: 'gray',
      light: 'white',
    },
    info: {
      main: 'white',
    },
    warning: {
      main: 'red',
    },
  },
  typography: {
    fontFamily: 'Lato',
  },
  components: {
    MuiButton: {
      variants: [
        {
          props: { variant: 'light', color: 'primary' },
          style: {
            textTransform: 'none',
            border: 'none',
            backgroundColor: 'primary.light',
            color: 'primary',
            borderRadius: 8,
            '&:hover': {
              backgroundColor: alpha('primary.main', 0.16),
              '&:active': {
                backgroundColor: alpha('primary.main', 0.32),
              },
            },
          },
        },
      ],
    },
  },
});

This works, except for the &:hover state properties, which don't know anything about the theme declaration, and so thus errors with MUI: Unsupported 'primary.main' color.

Is there a way I can use the theme colors like this inside of the theme declaration, or am I stuck overriding it at the theme wrapper level? I swear I saw this in some documentation somewhere, but can't find it.

Issue here is, you are trying to refer theme palette colors in a theme override definition, thats causing an issue. So alpha method parameter is unrecogizable.

To access your theme paletter color, define it separately first and then access it.

const globalTheme = createTheme({
  palette: {
    primary: {
      main: purple[500]
    },
    secondary: {
      main: "#11cb5f"
    }
  }
});


// inside button override
 "&:hover": {
    backgroundColor: alpha(globalTheme.palette.primary.main, 0.16)
 },

check working example here - https://codesandbox.io/s/mui-button-variant-override-e18vg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM