简体   繁体   中英

Material UI Toggle Button - can't change background color when selected

I'm trying to use the Material UI Toggle Button kind of like a radio button to give the user 2 choices to a given question.

It's functioning mostly as expected, but when trying to adjust the style for when each toggle button is selected, I can't get the Toggle Button background color to change. I'm using the classes prop on the ToggleButton component, and using the "selected" rule within that prop. Certain css properties (such as padding & boxShadow) are working, but others (including backgroundColor) are not. My goal is to make the Toggle button have a blue background when selected, but so far I can't get it to display differently than the darker grey background when selected.

I'm using React, along with Formik and Formik-Material-UI. Here is my code:

const useStyles = makeStyles((theme) => ({
  toggleButton: {
    backgroundColor: 'blue',
    border: [10, 'solid', 'black'],
    padding: 10,
    boxShadow: [
      [0, 0, 0, 1, 'blue'],
    ],

  }
}));

export function ScheduleAndServices(props) {
  const classes = useStyles(props);

return (

            <Field 
              component={ToggleButtonGroup} 
              name="requestType" 
              type="checkbox" 
              exclusive
            >
              <ToggleButton 
                value="ps" 
                aria-label="Temporary/Occasional" 
                selected={values.requestType === "ps" ? true : false}
                classes={{selected: classes.toggleButton}}
              >Temporary/Occasional   
              </ToggleButton>
              
              <ToggleButton 
                value="reg" 
                aria-label="Regular"
                selected={values.requestType === "reg" ? true : false}
              >Regular
              </ToggleButton>
            </Field>
);
}

Try that in your global css or scss file:

 button.MuiToggleButton-root.Mui-selected { background-color: #1f792f !important; border-color: #000 !important; }

Create new class and dont forget to use !important to override the backgroundColor of "Mui-selected" class

classes= useStyle({
newClass { backgroundColor:'red!important'},
})

<ToggleButton 
classes={{ 
selected:clasess.newClass,
.
.
.
}}
value=''
/>
  const useStyles = makeStyles(theme => ({
    ToggleButton : {
        '&.MuiToggleButton-root.Mui-selected': {
            backgroundColor: theme.palette.common.white,
        }
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM