reactjstypescriptmaterial-uireact-tsxcss-in-js

How to make an MUI 5 checkbox & label change color on hover?


I'd like to have a checkbox with a label in a wrapper. When the wrapper is hovered everything should change color. See the image:

enter image description here

Here is my code:

const styles = {formControlLabel:{
  color:'#d7dae0',
  border: '1px solid white',
  span: {
    color: '#d7dae0', 
    '&:hover':{border: '1px solid red'},
  }
},
}}

export function MyCheckbox(){
  return(
    <FormControlLabel
      control={<Checkbox />}
      label={'test'}
      sx={styles.formControlLabel}
    />
  )
}

I've tried many different things, but this is the closest I've come. I can't seem to put a '&:hover' on the formControlLabel styles at the top level - it has to be imbedded in another element. Why is that?

Sandbox: https://codesandbox.io/s/magical-feynman-lzy1e2?file=/src/App.tsx


Solution

  • You need to change your :hover to your parent and set borderColor in the parent and having span inside the :hover parent, it will change to red at the same time

    Codesandbox Demo


    const styles = {
      formControlLabel: {
        border: "1px solid",
        p: "8px",
        m: "20px",
        "&:hover": {
          borderColor: "red",
          span: {
              color: "red"
          },
        }
      }
    };