How to use pseudo-selectors in styleOverrides in MUI v5 Theming

Viewed 336

The MUI(v5)'s documentation has given this example:

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          // How to use pseudo-class here?
          // I've tried this but it doesn't work:
          // "&:hover": {
          //   backgroundColor: "#000"
          //  }
          fontSize: '1rem',
        },
      },
    },
  },
});

However, what if I want to add CSS style to the Button when it's hovered (or other pseudo-class states)? Would those be possible with styleOverrides as well?

1 Answers

Hi your code works perfectly in my repo.

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          '&:hover': {
            backgroundColor: '#000',
          },
          fontSize: '1rem',
        },
      },
    },
  },
});

however if you are creating theme then you should also use theme.pallete and other theme options rather than directly adding css colors in button.

below is how I create custom mui button.

const myTheme = {
  ...
  components: {
    MuiButton: {
      styleOverrides: {
        root: ({ ownerState, theme }) => ({
          textTransform: 'capitalize',
          fontSize: '0.75rem',
          fontWeight: 500,
          padding: '10px 16px 10px 16px',
          // '&:hover': { 
          //   backgroundColor: theme.palette.primary.dark,
          // },  // here worked as well 
          ...(ownerState.variant === 'semicontained' && {
            color: theme.palette.primary.main,
            backgroundColor: theme.palette.primary.light,
          }),
        }),
      },
    },
  },
};

export default myTheme;
Related