Uncategorized

React Material UI Create and Customize Checkbox Tutorial

Pinterest LinkedIn Tumblr

To create and customize a checkbox in React using Material-UI, you can use the Checkbox component. Here is an example:

Copy codeimport { Checkbox, FormControlLabel } from "@material-ui/core";

function CustomCheckbox() {
  const [checked, setChecked] = React.useState(false);

  return (
    <FormControlLabel
      control={
        <Checkbox
          checked={checked}
          onChange={(event) => setChecked(event.target.checked)}
          color="primary"
        />
      }
      label="Remember me"
    />
  );
}

In this example, we first import Checkbox and FormControlLabel from ‘@material-ui/core’. We use the Checkbox component and create a state variable called “checked” to keep track of the checkbox’s checked state. The “checked” prop is set to the value of the “checked” state variable. We also handle the onChange event for the checkbox and update the “checked” state variable with the value of the “checked” property of the event’s target.

We also wrap the checkbox component with FormControlLabel component and pass label prop to it.

You can customize the checkbox using the various props available on the Checkbox component, such as “color”, “size”, “disableRipple”, etc.

For example, you can change the color of the checkbox to “primary” by setting the “color” prop to “primary”, as shown in the example above.

You can also customize the label and style it as you like.

Copy code <FormControlLabel
      control={
        <Checkbox
          checked={checked}
          onChange={(event) => setChecked(event.target.checked)}
          color="primary"
        />
      }
      label="Remember me"
      style={{color: "green"}}
    />

In this example, I have added style to the label of the checkbox and change the color to green.

You can also customize the checkbox icon by passing the icon to Checkbox component.

Copy code <Checkbox
          icon={<FavoriteIcon style={{color: "red"}}/>}
          checkedIcon={<FavoriteIcon style={{color: "green"}}/>}
          checked={checked}
          onChange={(event) => setChecked(event.target.checked)}
        />

In this example, I have used a custom icon for the checkbox and changed the color of the icon when the checkbox is selected.

Write A Comment