How to create controlled switches with form groups in Material UI?


Switches in React MUI are a type of input element that allows the user to choose any one state, commonly an on or off state. These are commonly used to adjust settings on mobile devices. It is simply a check type button that helps toggle one of the two pre-defined states.

In this article, we will learn how to create controlled switches with form groups in Material UI. The reason for using FormGroup is that it provides a wrapper that allows grouping the selection control components and provides an easier API.

Steps to create controlled switches

Below are the steps for creating a controlled switch component in Material UI, with their respective syntaxes −

Step 1: Create a React Application

Before we move further to create sliders, we must have a React application. To create a new React app, run the below commands in your terminal −

npx create react app sliderproject

Once the project is created, navigate to its directory by running −

cd sliderproject

Step 2: Install the material UI

Once you have created the react app, it's time to install the Material UI into the react application. To install MUI, run the following command −

npm install @mui/material @emotion/react @emotion/styled

Step 3: Define the FormGroup along with Switch

Now, let’s import and define the switch component using Form Group −

<FormGroup>
   <FormControlLabel
      control={
         <Switch
            checked={checked}
            onChange={handleSwitch}
            inputProps={{ 'aria-label': 'controlled-switch' }}
         />
      }
      label="Controlled Switch 1"
   />
   <FormControlLabel
      control={
         <Switch
            checked={checked}
            onChange={handleSwitch}
            inputProps={{ 'aria-label': 'controlled-switch' }}
         />
      }
      label="Controlled Switch 2"
   /> 
   …
</FormGroup>

Step 4: Run The Project

To run the react MUI application, run the below command in the terminal −

npm run start

That's all! Now we have successfully learned the steps to create controlled switches with Form group in MUI.

Switch API

  • <Switch> − This API is used to create a switch component to toggle a state on or off in React MUI.

Props

  • "checked" − is used to indicate whether the component should be checked or not.

  • "checkedIcon" − is used to specify the icon that should be displayed when the component is checked or switched.

  • "classes" − allows you to customize or add styles to the components.

  • "color" − lets you choose colors, for switch components.

  • "defaultChecked" − sets a default value for when the switch's not controlled.

  • "disabled" − disables the switch component preventing user interaction.

  • "disableRipple" − turns off the effect in the switch component.

  • "edge" − adds negative padding on one side of the component.

  • "icon" − allows you to add icons that will be displayed when unchecked or unswitched.

  • "id" − assigns an ID attribute to an input element associated with this switch component.

  • "inputProps" − applies attributes to the input element of this switch.

  • "inputRef" − passes a reference to an input element within this switch.

  • "onChange" − specifies a callback function that will be triggered when theres a change in value, for this switch.

  • required − This prop is used to define the switch component as a required element.

  • size − This prop is used to change the size of the slider.

  • sx − This prop is used to add styles in Material UI.

  • value − This prop is used to add a value to the switch.

Example

In this example, we have created the basic control switches that are grouped in the FormGroup component and Material UI.

import React from "react";
import { FormControl, FormControlLabel, FormGroup, Switch } from "@mui/material";
import { useState } from "react";

const App = () => {
   const [swt, setSwt] = useState({
      java: false,
      cpp: true,
      javascript: false,
      python: true,
   });

   const handleSwitch = (e) => {
      setSwt({
         ...swt,
         [e.target.name]: e.target.checked,
      });
   };

   return (
      <div style={{
            padding: 40,
            width: '50%'
         }}>
         <FormControl component="fieldset" variant="standard">
            <FormGroup>
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.java}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="java"
                     />
                  }
                  label="Java"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.cpp}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="cpp"
                     />
                  }
                  label="C++"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.javascript}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="javascript"
                     />
                  }
                  label="JS"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.python}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="python"
                     />
                  }
                  label="Python"
               />
            </FormGroup>
         </FormControl>
      </div>
   );
};

export default App;

Output

Example

In this example, the switches have been created with the control states, and the labels are placed in different positions.

import React from "react";
import { FormControl, FormControlLabel, FormGroup, Switch } from "@mui/material";
import { useState } from "react";

const App = () => {
   const [swt, setSwt] = useState({
      java: false,
      cpp: true,
      javascript: false,
      python: true,
   });

   const handleSwitch = (e) => {
      setSwt({
         ...swt,
         [e.target.name]: e.target.checked,
      });
   };

   return (
      <div style={{padding: 40,width: '50%'}}>
         <FormControl component="fieldset" variant="standard">
            <FormGroup>
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.java}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="java"
                     />
                  }
                  label="Java"
                  labelPlacement="top"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.cpp}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="cpp"
                     />
                  }
                  label="C++"
                  labelPlacement="right"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.javascript}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="javascript"
                     />
                  }
                  label="JS"
                  labelPlacement="left"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.python}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="python"
                     />
                  }
                  label="Python"
                  labelPlacement="bottom"
               />
            </FormGroup>
         </FormControl>
      </div>
   );
};
export default App;

Output

Example

The example demonstrates the creation of control switches with form groups in different sizes and colors.

import React from "react";
import { FormControl, FormControlLabel, FormGroup, Switch } from "@mui/material";
import { useState } from "react";

const App = () => {
   const [swt, setSwt] = useState({
      java: false,
      cpp: true,
      python: true,
   });

   const handleSwitch = (e) => {
      setSwt({
         ...swt,
         [e.target.name]: e.target.checked,
      });
   };

   return (
      <div style={{padding: 40,width: '50%'}}>
         <FormControl component="fieldset" variant="standard">
            <FormGroup>
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.java}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="java"
                        size="small"
                        color="info"
                     />
                  }
                  label="Java"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.cpp}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="cpp"
                        size="medium"
                        color="success"
                     />
                  }
                  label="C++"
               />
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.python}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="python"
                        size="large"
                        color="warning"
                     />
                  }
                  label="Python"
               />
            </FormGroup>
         </FormControl>
      </div>
   );
};
export default App;

Output

Example

The example demonstrates how to create controlled switches with the form groups in Material UI. Here we have created a switch that is controlled by the state management in React. Now, when the switch is toggled, it displays ON; otherwise, it displays OFF.

import React from "react";
import { FormControl, FormControlLabel, FormGroup, Switch } from "@mui/material";
import { useState } from "react";

const App = () => {
   const [swt, setSwt] = useState(false);
   const handleSwitch = (e) => {
      setSwt(!swt);
   };

   return (
      <div style={{padding: 40,width: '50%'}}>
         <FormControl component="fieldset" variant="standard">
            <FormGroup>
               <FormControlLabel
                  control={
                     <Switch
                        checked={swt.java}
                        onChange={handleSwitch}
                        inputProps={{ 'aria-label': 'controlled-switch' }}
                        name="Switch"
                        color={swt ? "success": "default"}
                        size="medium"
                     />
                  }
                  label={swt ? "ON" : "OFF"}
               />
            </FormGroup>
         </FormControl>
      </div>
   );
};
export default App;

Output

Conclusion

This article covers the complete process of creating the controlled switches with the help of Form Groups in React MUI. The different examples, along with their respective outputs, have been discussed in this article.

Updated on: 31-Oct-2023

34 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements