I'm trying to target the span, but haven't been able to do so. I want to be able to change the background color of the span when the checkbox is checked.
<div className={classes.container}>
<input type="checkbox" id="checkboxid" />
<label className={classes.label} htmlFor="checkboxid">
<span className={classes.labelText}>Target</span>
</label>
</div>
container: {
'& input:checked': {
'& label': {
'& $labelText': {
background: 'red'
}
}
}
}
CodePudding user response:
While label is not inside the input but a sibiling you need to make use of the css sibling selector
In your context
const useSpanStyles = makeStyles({
container: {
'& input:checked label': {
'& span': {
background: 'red'
}
},
},
label: {},
labelText: {}
});
export function ComponentXYZ(){
const classes = useSpanStyles();
return (
<div className={classes.container}>
<input type="checkbox" id="checkboxid" />
<label className={classes.label} htmlFor="checkboxid">
<span className={classes.labelText}>Target</span>
</label>
</div>
);
}
To be honest with you, if you are using MUI you should've used their components as its easier to compose and build UI with
Here's my suggestion
function ComponentXYZ(){
const [checked, setIsChecked] = useState(false);
const checkedHandler = useCallback(function _checkedHandler(event: any) {
setIsChecked(event.target.checked);
}, []);
return (
<div>
<FormGroup>
<FormControlLabel
control={<Checkbox
checked={checked}
onChange={checkedHandler}
/>}
label={
<Typography style={{ background: checked ? 'red' : 'inherit' }}>
{'Label That change color'}
</Typography>
}
/>
</FormGroup>
</div>
);
}
