Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use MUI Checkbox Component to Make Interactive Apps

Are you looking to add multiple choice field to your web application? The Material UI or MUI Checkbox component lets you add a checkbox field to your website. This field can be helpful when building an interactive application such as a Quiz application or an eCommerce site.

In this tutorial, we’ll explore how to implement Checkboxes in React using the material UI Checkbox component. Before we get started, here’s a brief introduction to material UI and checkboxes.

What Is Material UI Checkbox Component?

Material UI is one of the most popular frontend development libraries that provides components to build any part of your website with minimal code.

One of the components it supports is the Checkbox component. This component easily adds multiple-choice fields to a form in your application. The checkbox can either be controlled or uncontrolled.

In a controlled checkbox, you can access the state of the component. In contrast, an uncontrolled checkbox doesn’t store the component’s state or handle state changes.

MUI is a preferred choice for most developers. This is evident in its stats according to NPM trends of over 1.5 million weekly downloads with over 86k stars on GitHub.

Material UI weekly stats

If you’re using material UI for your project, consider using Purecode to easily access over 10k ready-made templates to speed up your development process. Access our ready-made templates.

Implementing Material UI Checkbox Component

Now you know what MUI library is and why it is a preferred choice for most developers. Let’s explore how to install React and the MUI library.

Prerequisite

Before creating material UI Checkboxes, you need to have the following:

  • NPM installed on your machine.

  • Basic knowledge of JavaScript and React.

If you need help getting started with React, check out the video tutorial below.

Installing React and Material UI

We’ll use the create-react-app package to install a boilerplate React application. To start, open your terminal window and navigate to the directory you want to install React.

After that, run the command below.

npx create-react-app checkbox-basics

After the installation completes, you’ll need to navigate into the project folder.

React installation in the terminal
cd checkbox-basics

Inside the project directory, you need to install the material UI library. For this, run the command below.

Npm:

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

Yarn:

yarn add @mui/material @emotion/react @emotion/styled

Note: Material UI uses Emotion as its default styling engine. But you can also use Styled Component if you prefer the library.

Using the Material UI Checkbox Component

After installing React and Material UI core, proceed to import the library into your React application. The Material UI checkbox component is a subset of material UI.

Now, let’s create a basic checkbox in our React app. Start by copying and pasting the code below into App.js to import the Checkbox component.

import Checkbox from "@mui/material/Checkbox";

The basic usage is to use the <Checkbox> component in the App.js function. To do that, add the component in the App function to create a checkbox.

import Checkbox from "@mui/material/Checkbox";

const App = () => {
   return (
       <Checkbox defaultChecked />
   );
}

export default App;

In the frontend, you’ll see the checkbox visible on the browser. When the user clicks on the checkbox, it will have a blue tick, indicating the checkbox has been checked.

basic checkbox component

In the next sections, we’ll cover basic and advanced customizations of the checkbox component.

Customizing Material UI Checkbox Component

Material UI core has a lot of built-in customizations that make it easy to style your components. You can update your checkbox’s color and text size with minimal code. We’ll explore various customization options here.

Note: The customizations in this tutorial follow material UI version 5. If you’d like to use material UI framework v4, check the MUI v4 documentation to learn more. Here is a video tutorial to help you get started.

Checkbox Attributes

Attributes are props that can be passed to the checkbox component. Below is a list of available attributes that the checkbox component supports.

  • Label

  • Color

  • Size

  • Default Checked

  • Disabled

We’ll cover how these props work with examples in the following sections.

Material UI Checkbox Label and Placement

A good use case for the checkbox component is when creating forms for your project. You can use the FormControl component to create your form fields.

Within the FormControlLabel component, you can specify a checkbox component in the control prop. Then, use the label placement prop to choose where you want the label for the checkbox to show.

Here is an example implementation.

import * as React from 'react';
import Checkbox from '@mui/material/Checkbox';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';

function App() {
  return (
    <FormControl component="fieldset">
      <FormLabel component="legend">Label placement</FormLabel>
      <FormGroup aria-label="position" row>
        <FormControlLabel
          value="top"
          control={<Checkbox />}
          label="Top"
          labelPlacement="top"
        />
        <FormControlLabel
          value="start"
          control={<Checkbox />}
          label="Start"
          labelPlacement="start"
        />
        <FormControlLabel
          value="bottom"
          control={<Checkbox />}
          label="Bottom"
          labelPlacement="bottom"
        />
        <FormControlLabel
          value="end"
          control={<Checkbox />}
          label="End"
          labelPlacement="end"
        />
      </FormGroup>
    </FormControl>
  );
}

export default App;

In the code above, we’re importing FormGroup, FormControl, FormControlLabel, and FormLabel from the material UI library.

To create a form in material UI, you’ll need to wrap the entire form in the FormControl component. Then, all fields will be within the FormGroup component.

We use the FormControlLabel component to specify the form fields we want to use. To use a checkbox as the form field, you’ll need to pass it as a parameter in the control prop. The label prop is used to define the label of the checkbox component.

The labelPlacement prop controls the position of checkbox item labels in the form. The supported placements include:

  • Top: The label is placed above the checkbox

  • Bottom: Label is placed below the checkbox

  • Start: Label is placed before the checkbox

  • End: Label is placed after the checkbox

When you save and preview the code above, you’ll see checkboxes with their respective label placements.

Checkbox label placements

How to Customize MUI Checkbox Sizes

Material UI framework provides props to update the sizes of components it supports. To update the sizes of checkbox items, we use the size prop. Below are the default theme sizes material UI core supports:

  • Small

  • Medium (default)

  • Large

You can pass any of the props to update the size of your checkboxes.

<Checkbox defaultChecked size='small'/>
<Checkbox size='medium'/>
<Checkbox size='large' />
MUI checkbox sizes

Making Material UI Checkbox Checked by Default

To make the checkbox field checked by default, simply pass the checked or defaultChecked prop to the component.

<Checkbox defaultChecked />
<Checkbox checked />

Checkbox components are unchecked by default. However, you can pass in the unchecked prop to explicitly specify the state as an unchecked checkbox.

<Checkbox unchecked />

Checkbox States

Checkbox component can have three states by default:

  • Checked

  • Unchecked

  • Indeterminate

These states can be passed as props to checkbox components.

<Checkbox unchecked color='info' />
<Checkbox checked color='secondary' />
<Checkbox
   indeterminate
   inputProps={{ 'aria-label': 'indeterminate checkbox' }}
   color='success'
/>
material UI checkbox state

Disabled Checkboxes

A disabled checkbox does not allow users to update the component’s state. It is usually seen as a grey checkbox.

<Checkbox checked disabled />
<Checkbox disabled />

In the example above, we added two disabled checkbox items. The first item has the checked prop, while the second uses the default unchecked value.

Disabled checkbox

Indeterminate Checkboxes

MUI Checkbox component’s indeterminate prop is a boolean property that defines whether the checkbox is in an indeterminate state or not. The checkbox will be rendered as a horizontal line if the indeterminate prop is true, denoting that it is neither checked nor unchecked.

This can be useful when creating a checkbox that should have children components. You can use the indeterminate prop to display the checkbox in an indeterminate state to show the user that some but not all items in a list it represents are checked.

A Material UI checkbox might be displayed in an uncertain state using the indeterminate prop, as shown in the following example:

import {useState} from 'react';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';

function IndeterminateCheckboxExample() {
  const [checked, setChecked] = useState([true, false]);

  const handleChange1 = (event) => {
    setChecked([event.target.checked, event.target.checked]);
  };

  const handleChange2 = (event) => {
    setChecked([event.target.checked, checked[1]]);
  };

  const handleChange3 = (event) => {
    setChecked([checked[0], event.target.checked]);
  };

  const children = (
    <Box sx={{ display: 'flex', flexDirection: 'column', ml: 3 }}>
      <FormControlLabel
        label="Option 1"
        control={<Checkbox checked={checked[0]} onChange={handleChange2} />}
      />
      <FormControlLabel
        label="Option 2"
        control={<Checkbox checked={checked[1]} onChange={handleChange3} />}
      />
    </Box>
  );

  return (
    <div>
      <FormControlLabel
        label="Parent"
        control={
          <Checkbox
            checked={checked[0] && checked[1]}
            indeterminate={checked[0] !== checked[1]}
            onChange={handleChange1}
          />
        }
      />
      {children}
    </div>
  );
}

export default IndeterminateCheckboxExample;

In the code above, we are using the useState hook to store the state of the children checkbox components. We specify that the parent component will only be checked if both children checkboxes are selected.

Then, we pass the indeterminate prop to the main checkbox and use a comparison operator to say this prop will be true if both children checkboxes are not equal.

When you run the code above in your React app, you’ll see the parent component with the conditional indeterminate prop.

It will be partially checked if one of the children components is checked, denoting the indeterminate prop is true. However, if both options are checked, the main checkbox will also be checked. Denoting the indeterminate prop is false.

Indeterminate checkbox example

Using Material UI Checkbox Component as Icons

If you’d like, you can use MUI icons as the labels for your checkbox components. Here is an example implementation.

import * as React from 'react';
import Checkbox from '@mui/material/Checkbox';
import FavoriteBorder from '@mui/icons-material/FavoriteBorder';
import Favorite from '@mui/icons-material/Favorite';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import BookmarkIcon from '@mui/icons-material/Bookmark';

const label = { inputProps: { 'aria-label': 'Checkbox demo' } };

export default function IconCheckboxes() {
  return (
    <div>
      <Checkbox {...label} icon={<FavoriteBorder />} checkedIcon={<Favorite />} />
      <Checkbox
        {...label}
        icon={<BookmarkBorderIcon />}
        checkedIcon={<BookmarkIcon />}
      />
    </div>
  );
}

You’ll need to ensure the MUI icons library is installed on your project’s root directory.

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

Here’s how the check boxes will look with icon labels.

Checkboxes using MUI icons

Updating the Color of a Checkbox

Like other material UI components, you can update the color of checkboxes using the color prop. Below are the default theme colors Material UI core supports.

  • Primary (Default)

  • Secondary

  • Success

  • Warning

  • Error

  • Info

<Checkbox defaultChecked />
<Checkbox defaultChecked color="secondary" />
<Checkbox defaultChecked color="success" />
<Checkbox defaultChecked color="default" /> 
<Checkbox defaultChecked color="info" /> 
<Checkbox defaultChecked color="warning" /> 
<Checkbox defaultChecked color="error" /> 
Checkbox color variants

You can also define a custom color using the sx prop in the checkbox component.

<Checkbox
  defaultChecked
  sx={{
    color: '#a61107',
    '&.Mui-checked': {
      color: '#f56358',
    },
  }}
/>

The color prop controls the color of the checkbox’s unchecked state. If you’d like to specify a color for the checked state of the component, use the ‘&.Mui-checked‘ prop.

Updating MUI Checkbox Component in React

Earlier we mentioned that material UI checkboxes can be used as controlled or uncontrolled components. Using a controlled checkbox is ideal since we’d want to access the user’s selected value.

To make a checkbox controlled, we’ll need to store its value in a state. Then, use the onChange event handler to update the state variable each time the user selects an option.

The next section will show how to use the useState hook to update the component’s state.

Setting Material UI Checkbox State with React useState Hook

Just like any React component, you can handle state changes on the Checkbox component. Here is an example implementation.

import { useState } from 'react';
import Checkbox from "@mui/material/Checkbox";


function CheckboxExample() {
  const [checked, setChecked] = useState(false);

  const handleChange = (event) => {
    setChecked(event.target.checked);
    console.log(checked)
  };

  return (
    <div>
      <Checkbox
        checked={checked}
        onChange={handleChange}
        inputProps={{ 'aria-label': 'primary checkbox' }}
      />
    </div>
  );
}

export default CheckboxExample;

In the code above, we use the useState hook to store the checked value of the Checkbox component. In the handleChange function, you can specify any action you want to perform. For this example, we are just logging the boolean value of the checked state.

Updating checkbox state

When to Use Checkbox Over Radio buttons

Choosing between Checkboxes and Radio buttons is a common pain point for many web developers. Although they function similarly, their default behavior varies.

Checkboxes allow the user to select one or more options from a set. In contrast, radio buttons allow users to select a single option by default.

So, if you want to allow users to choose any number of options from the multiple options field, using checkboxes is ideal for this use case. For instance, when implementing a newsletter option form, the user can optionally select the checkbox to signup for your newsletter or proceed without it.

However, if the options on your multiple choice field are mutually exclusive and users can only select one option from the set, we suggest using radio buttons. An example is implementing a quiz app with multiple options whereby a user can only select one correct answer from the set.

Frequently Asked Questions

Below, we’ve answered some top questions about using the Checkbox component in React.

How to use Material UI disabled prop?

To disable a Checkbox component, simply add the disabled prop to it. Adding this prop prevents the user from selecting the checkbox option.

<Checkbox disabled />

When enabled, the user won’t be able to select the checkbox component.

How do I create a checkbox group in React?

The quickest way to create a checkbox group in React is with the FormGroup component that MUI provides. Within the FormGroup component, use the FormControlLabel component to define your checkboxes. You’ll need to pass the checkbox to the control prop as a parameter. Here is an example.

// ...
<FormGroup>
   <FormControlLabel
	label="Option 1"
	control={<Checkbox color="primary" />} 
   />
   <FormControlLabel
	label="Option 2"
	control={<Checkbox color="success" />} 
   />
</FormGroup>

// ...
Checkbox group

How to make a checkbox group in HTML?

You can define a checkbox group in HTML using the <input> element and setting the type parameter to checkbox.

<form action="/">
  <h3>Choose the subjects you are interested in</h3>
  <input type="checkbox" id="math" name="math" value="math">
  <label for="vehicle1"> Mathematics</label><br>
  <input type="checkbox" id="science" name="science" value="science">
  <label for="vehicle2"> Basic Science</label><br>
  <input type="checkbox" id="coding" name="vehicle3" value="coding">
  <label for="vehicle3"> Programming</label><br><br>
  <input type="submit" value="Submit">
</form>

Here is how the code will look on the frontend.

Checkbox example in HTML

Explore Other Styling Tutorials

If you enjoyed this tutorial, check out our other styling tutorials to improve your skills.

Putting Material UI Checkbox into Action

Using checkboxes on your project allows users to select one or more options from a set. This can be useful when conducting surveys or building a Quiz application.

In this tutorial, we’ve shown you how to use the material UI Checkbox component in your React application. We also explained the various available styling options and handling state changes in the Checkbox component.

If you’re using material UI for your project, check out some of Purecode’s templates. Purecode provides over 10k AI-generated templates that can be integrated into web applications that use React and Material UI for styling.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer