Search code examples
reactjsswitch-statementmaterial-uislidetoggle

Add text to Switch formcontrol and change it in toggle using material ui


I am using Material UI's Switch component and I want to add text inside it. Also I need to make it square in shape.

How to I add text inside the Switch component. It should say on when selected and off when default. I am using Material UI's Switch inside Formcontrol in reactjs form.

<FormControlLabel 
  label="Private ? "
  labelPlacement="start"
  control={
    <Switch
       checked={this.state.checked}
       onChange={this.handleChange}
       color='primary'
    />
  } 
/>

Solution

  • Here is an example of how to change the text based on the state of the Switch as well as the styles for a square Switch:

    import React from "react";
    import FormControlLabel from "@material-ui/core/FormControlLabel";
    import Switch from "@material-ui/core/Switch";
    import { withStyles } from "@material-ui/core/styles";
    
    const styles = {
      // use "icon" instead of "thumb" in v3
      thumb: {
        borderRadius: 0
      }
    };
    class SwitchLabels extends React.Component {
      state = {
        checked: true
      };
    
      handleChange = event => {
        this.setState({ checked: event.target.checked });
      };
    
      render() {
        return (
          <FormControlLabel
            control={
              <Switch
                classes={this.props.classes}
                checked={this.state.checked}
                onChange={this.handleChange}
                value="checked"
                color="primary"
              />
            }
            labelPlacement="start"
            label={this.state.checked ? "On" : "Off"}
          />
        );
      }
    }
    
    export default withStyles(styles)(SwitchLabels);
    

    Edit Switch text change