I am using Material UI's Switch component and I want to add text inside it. I want something like in the image below.

Here's my code.
import React from 'react';
import Switch from '@material-ui/core/Switch';
export default function Switches() {
const [state, setState] = React.useState({
checkedA: true,
});
const handleChange = (event) => {
setState({ ...state, [event.target.name]: event.target.checked });
};
return (
<div>
<Switch
checked={state.checkedA}
onChange={handleChange}
name="checkedA"
inputProps={{ 'aria-label': 'secondary checkbox' }}
/>
</div>
);
}
I already searched for the answer and found How to add text inside a Switch Component in Material-UI React? and Add text to Switch formcontrol and change it in toggle using material ui . Both of them were not helpful for me.
You can achieve this by adding pseudo-elements :after and :before to Switch's track inner element with text inside them. Add content property to these pseudo-elements with the desired text and place them using absolute positioning.
To override Material-UI components style you can use makeStyles hook generator.
To reach component's inner elements you can use prop classes or regular global class names like .MuiSwitch-track. See https://material-ui.com/customization/components/
Please check my codesandbox example:
https://codesandbox.io/s/confident-euler-98tqo?file=/src/App.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With