Material UI is a Material Design library made for React.

It’s a set of React components that have Material Design styles.

In this article, we’ll look at how to add switches with Material UI.

Switches

Switches are toggles that let us set something on or off.

To add one, we use the Switch component.

For instance, we can write:

import React from "react";
import Switch from "@material-ui/core/Switch";

export default function App() {
  const [checked, setChecked] = React.useState();
  const handleChange = event => {
    setChecked(event.target.checked);
  };
  return (
    <div className="App">
      <Switch checked={checked} onChange={handleChange} name="checked" />
    </div>
  );
}

We set the checked prop with the checked state.

onChange has a function that runs when we click on the toggle.

event.target.checked has the checked value so that we use it to change the checked state.

We can change the color with the color prop.

For example, we can write:

import React from "react";
import Switch from "@material-ui/core/Switch";

export default function App() {
  const [checked, setChecked] = React.useState();
  const handleChange = event => {
    setChecked(event.target.checked);
  };
  return (
    <div className="App">
      <Switch
        color="primary"
        checked={checked}
        onChange={handleChange}
        name="checked"
      />
    </div>
  );
}

With the color prop, we changed the color.

#web-development #technology #software-development #javascript #programming #switches

Material UI — Switches
7.05 GEEK