What's the right way to override colors with MUI withStyle and TypeScript and next.js?

Viewed 50

I have:

const Button: React.FC<ButtonProps> = ({
  label,
  size,
  variant = 'primary',
  disabled = false,
}: ButtonProps) => {
  const classes = useStyles();
  return (
    <MaterialButton
      className={`${classes.buttonBase} size-${size}`}
      disabled={disabled}
    >
      {label}
    </MaterialButton>
  );
};

and

const useStyles = makeStyles(() => ({
  buttonBase: {
    background:'#000000',
    color: '#ffffff',

However, if variant is secondary, I want to basically swap the background and color. How do I go about doing this?

1 Answers

You can set it in your theme. The example below is for using the variant="contained" with color="secondary"

export const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        containedSecondary: {
          backgroundColor: '#808080',
          color: '#FFFFFF',
          '&:hover': {
            backgroundColor: '#565656',
          },
        },
      }
    }
  }

<Button variant="contained" color="secondary">Test button</Button>

Or if you want to set the style in your component you can set up a variant for the secondary like this. Here is a working codesandbox

const useStyles = makeStyles({
  primary: {
    backgroundColor: "purple",
    color: "#FFF"
  },
  secondary: {
    backgroundColor: "red",
    color: "#FFF"
  }
});

<Button className={classes.secondary}>Secondary</Button>
<Button className={classes.primary}>Primary</Button>
Related