Checkbox

Import
import { Checkbox, CheckboxGroup } from "reshaped";
import type { CheckboxProps, CheckboxGroupProps } from "reshaped";
Related components
Supports indeterminate state
Full keyboard navigation
Can be controlled and uncontrolled
Supports checkbox groups with custom rendering


Usage

Checkbox component works like native checkboxes, which means you can use its value property to define what will be passed to the form when submitted. Note that it's required to pass a name to the Checkbox.

Like all native inputs in React, Checkbox supports controlled and uncontrolled options. It becomes controlled when you use checked property, which means you have to control it with your state. An uncontrolled variant is used when you use the defaultChecked property, which lets you define the default state but let the browser handle the rest.

Note: You shouldn't be using both properties simultaneously, and React will throw a warning if that happens.

States

If there is an error related to the checkbox field, you can use a hasError flag.

To make Checkbox non-interactive, you can use the disabled flag. Like in a native checkbox, it will prevent onChange handler from triggering.

Note: Disabled state fades the component content. Even though it's not required to have a regular contrast ratio for disabled elements, make sure not to use it on gray background.

When Checkbox is used as a parent field for another checkbox group, you can use an indeterminate flag to display that some items in that group are selected. The JS API of the inputs controls the indeterminate state, so by default, it will check the Checkbox when you click it. If you want to avoid that — use a controlled component variant.

Composition

In products, we sometimes work with checkbox groups to select multiple values from a list of options. CheckboxGroup handles this kind of interaction and lets you work with multiple checkboxes represented with an array of values. At the same time, it doesn't enforce any specific layout, so you're free to use it with any layout components.

As you can see, name and onChange properties apply to all Checkbox components within its scope. You will get an array with the selected value logged into the console by choosing a specific Checkbox.

Same way as Checkbox can define its checked property, CheckboxGroup supports value and defaultValue to control the selection in the options list.

If you need to provide a label for a group of checkboxes, you can use the FormControl utility with the group flag turned on. That will resolve FormControl HTML tags correctly for a group of input fields.

Both Checkbox and CheckboxGroup support content composition. Since CheckboxGroup doesn't provide any markup, you can use it with any layout components. For the Checkbox component, you can render multiple elements as its children.

Accessibility

  • When using Checkbox without children, wrap it with a label element.
Previous