Neha Chaudhary
Neha Chaudhary

Reputation: 1279

Set selected background-color of MUI ToggleButton

I'm unable to set the background color when the toggle button is selected. Right now, the buttons work but don't have any specific color when one is selected. I want to have a default color to the Btn 1 and if the user selects any other button, that button should get the default color.

<Grid container direction='column'>
        <ToggleButtonGroup
          value={title}
          exclusive
          size='small'
        >
          <ToggleButton onClick={this.handleOnClick}>
            Btn 1
          </ToggleButton>
          <ToggleButton onClick={this.handleOnClick}>
            Btn 2
          </ToggleButton>
          <ToggleButton onClick={this.handleOnClick}>
            Btn 3
          </ToggleButton>
      </ToggleButtonGroup>

      </Grid>

Upvotes: 10

Views: 21210

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81723

Use &.Mui-selected selector to change the background color of the selected ToggleButton. You can see a list of state classes here:

import MuiToggleButton from "@mui/material/ToggleButton";
import { styled } from "@mui/material/styles";

const ToggleButton = styled(MuiToggleButton)({
  "&.Mui-selected, &.Mui-selected:hover": {
    color: "white",
    backgroundColor: '#00ff00'
  }
});

If you want to provide a selected color prop:

const ToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({
  "&.Mui-selected, &.Mui-selected:hover": {
    color: "white",
    backgroundColor: selectedColor
  }
}));
<ToggleButton value="left" selectedColor="#00abc0">
  <FormatAlignLeftIcon />
</ToggleButton>

Codesandbox Demo

Upvotes: 16

Related Questions