Reputation: 89
I'm trying to create a custom switch using the Material UI Switch component (found here). I have placed a label to the right of my switch, however, the placement is too close to the switch. I was wondering if there's a way to adjust the spacing between the switch and the label? Thank you. Here is my code:
return (
<FormGroup>
<Typography component="div">
<Grid component="label" container alignItems="center" spacing={1}>
<Grid item></Grid>
<Grid item>
<FormControlLabel
control={<AntSwitch checked={state.checkedC} onChange={handleChange} name="checkedC"/>}
label= {state.checkedC? 'On' : 'Off'}
labelPlacement="end"
/>
</Grid>
</Grid>
</Typography>
</FormGroup>
);
Upvotes: 1
Views: 2989
Reputation: 754
I've used flex and Stack
to do it in Material UI v5:
<Stack>
<FormControl>
<FormGroup>
<FormControlLabel
sx={{
justifyContent: 'space-between',
display: 'flex',
}}
label="Newsletter"
labelPlacement="start"
control={
<Switch
inputProps={{
'aria-label': 'Switch newsletter',
}}
/>
}
value="Newsletter"
/>
</FormGroup>
</FormControl>
</Stack>
Upvotes: 0
Reputation: 807
There's quite a few different ways you can tackle this issue. It's usually good etiquette to mention what you have tried. ;)
In any case, here's one approach, the Grid component:
<FormGroup>
<Typography component="div">
<Grid
component="label"
container
alignItems="center"
alignContent="space-between"
xs={12}
spacing={3}
>
<Grid item>
<Switch
checked={state.checkedB}
onChange={handleChange}
name="checkedB"
/>
</Grid>
<Grid item>{state.checkedA ? "On" : "Off"}</Grid>
</Grid>
</Typography>
</FormGroup>
Here's another approach using plain old CSS.
<FormGroup>
<Typography component="div">
<Switch
checked={state.checkedB}
onChange={handleChange}
name="checkedB"
/>
<span style={{paddingLeft:'2em'}}>{state.checkedA ? "On" : "Off"}</span>
</Typography>
</FormGroup>
You can see both in action here: https://codesandbox.io/s/grid-spacing-7w1kn
Please note that you are using a combination of Ant Design and Material Design components there in your original code snippet. This is probably unwise. Mixing CSS can lead to weird unintended side effects. In the code examples above, I swapped out the Ant Design Toggle for the Material Design one.
Upvotes: 0