Search code examples
cssreactjstypescriptmaterial-uiemotion

How can I set on hover behaviour for a MUI Button inside a ButtonGroup


Using MUI v5, the following code only half works. The first button is colored red (specifically, the border and text are red), however on hover, the color of the border changes to blue (the style is being inherited from the ButtonGroup which is blue by default).

How can I force the first button to keep its red (from theme.palette.error) border on hover, ideally the 'mui 5' way (ie using sx or emotion or something of this nature)?

Current behavior: the border and text of the first button are red, but the border becomes blue on hover.

Desired behavior: the border and text of the first button are always red.

Any help much appreciated :)

<ButtonGroup variant="outlined">
  <Button color="error">
    Again
  </Button>
  <Button>
    Good
  </Button>
</ButtonGroup>```

Solution

  • You can select the button group's hover class for first button and apply your desired styles in it. To style the first button in the button group, Mui uses this selector MuiButtonGroup-grouped:not(:last-of-type). By using this selector's pseudo class hover, you can customize the styles from the wrapper div. I've forked one the MUI examples for button groups on their docs site and applied css through the sx prop in the box.

    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        "& > *": {
          m: 1
        },
        ".MuiButtonGroup-grouped:not(:last-of-type):hover": { // class selector 
          borderColor: "red"
        }
      }}
    >
      <ButtonGroup size="small" aria-label="small button group">
        <Button key="one" color="error">
          One
        </Button>
        ,<Button key="two">Two</Button>
      </ButtonGroup>
    </Box>