John Glabb
John Glabb

Reputation: 1621

How to style ToggleButon in material-ui

I'm trying to style ToggleButton to override default color when it's selected. But it doesn't work.

const useStyles = makeStyles((theme) => ({   
  toggleButtonSelected: {
      "background-color": "red"
  }
}))

.......
<ToggleButtonGroup exclusive>
    <ToggleButton
        classes={{ selected: classes.toggleButtonSelected }}
        value="a" >
        Button A
    </ToggleButton>
    <ToggleButton
        classes={{ selected: classes.toggleButtonSelected }}
        value="b">
        Button B
    </ToggleButton>
</ToggleButtonGroup>

Upvotes: 1

Views: 420

Answers (1)

AnsonH
AnsonH

Reputation: 3256

Solution

Try to change your makeStyles styling to the following:

const useStyles = makeStyles((theme) => ({
  toggleButtonSelected: {
    "&.MuiToggleButton-root": {
      "background-color": "red"
    }
  }
}));

Edit on Code Sandbox

Explanation

Original specificity

Your original makeStyles styling is not working because it generates a CSS rule with selector of .makeStyles-toggleButtonSelected-1 (circled in red in the above screenshot), which is overridden by another rule with higher specificity.

With our new makeStyles styling, it generates a CSS rule with the selector having a higher selectivity than your original styling (circled in red in below). This new styling can successfully override the default styling.

New specificity

Upvotes: 1

Related Questions