2021年7月7日 星期三

[react, material-ui, switch] How to use the Switch component and change the label when toggled using material-ui

How to use the Switch component and change the label when toggled using material-ui

井民全, Jing, mqjing@gmail.com

Github: source

To update the component status from the UI Component, we can use React.useState to do this. It's easy to add a Switch component to the App and update the label by the following procedure. In addition, in Section 4, I'll show you how to debug the project using the vscode.


Enjoy!

By Jing.



1. Install

npx create-react-app my-app --template typescript

cd my-app

yarn add @material-ui/core


2. Usage

File: src/App.tsx

import Switch from '@material-ui/core/Switch'; 

import FormControlLabel from '@material-ui/core/FormControlLabel';  // label



function App() {

    const [state, setState] = React.useState({

        checkedA: true,

  });

  

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {

    setState({ ...state, [event.target.name]: event.target.checked }); // update new  state

  };


  return (

    <div>

      <FormControlLabel

        label={state.checkedA ? "On" : "Off"}

        control = {<Switch

            checked={state.checkedA}

            onChange={handleChange}

            color="primary"

            name="checkedA"

            inputProps={{ 'aria-label': 'primary checkbox' }}

          />}

        />

    </div>

  );

}



3. Clean

# add this to the package.json

"clean": "rm -fr node_modules"


4. Debug in VSCode

Step 1: Create a launch.json file that chooses chrome

Step 2: Change the port 


{

     "version": "0.2.0",

    "configurations": [

        {

            "type": "chrome",

            "request": "launch",

            "name": "Launch Chrome against localhost",

            "url": "http://localhost:3000",

            "webRoot": "${workspaceFolder}"

        }

    ]

}



Step 3: Build & Run service

yarn start


Step 4: Click Run from vscode 

 

5. References

  1. https://material-ui.com/components/switches/

  2. https://stackoverflow.com/questions/56128013/add-text-to-switch-formcontrol-and-change-it-in-toggle-using-material-ui