Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text inside the switch using material ui

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

enter image description here

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.

like image 841
Kundan Avatar asked Mar 11 '26 18:03

Kundan


1 Answers

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

like image 172
Pet'EmAll Avatar answered Mar 14 '26 06:03

Pet'EmAll