Checkbox
Checkboxes give users binary choices when presented with multiple options in a series.
Component
import { Checkbox } from '@base_ui/react/Checkbox';
Anatomy
The Checkbox component is composed of a root component and an indicator child component:
<Checkbox>
<Checkbox.Indicator />
</Checkbox>
The indicator can contain children, such as an icon:
<Checkbox>
<Checkbox.Indicator>
<MyCheckIcon />
</Checkbox.Indicator>
</Checkbox>
The indicator conditionally unmounts its children when the checkbox is unchecked. For CSS animations, you can use the keepMounted prop to transition visibility and opacity for example:
<Checkbox>
<Checkbox.Indicator keepMounted>
<MyCheckIcon />
</Checkbox.Indicator>
</Checkbox>
Custom structure
Use the render prop to override the rendered checkbox or indicator element with your own components:
<Checkbox render={(props) => <MyCheckbox {...props} />}>
<Checkbox.Indicator render={(props) => <MyCheckboxIndicator {...props} />} />
</Checkbox>
To ensure behavior works as expected:
- Forward all props: Your component should spread all props to the underlying element.
- Forward the
ref: Your component should useforwardRefto ensure the Checkbox components can access the element via a ref.
A custom component that adheres to these two principles looks like this:
const MyCheckbox = React.forwardRef(function MyCheckbox(props, ref) {
return <button ref={ref} {...props} />;
});
Indeterminate state
To make the checkbox indeterminate, add the indeterminate prop to override the appearance of the checkbox. The checkbox remains in an indeterminate state regardless of user interaction until set back to false.
An indeterminate checkbox's main use case is representing the state of a parent checkbox where only some of its children are checked:
It's a visual-only state, so it can still have its internal checked state change.
Hook
import { useCheckbox } from '@base_ui/react/useCheckbox';
The useCheckbox hook lets you apply the functionality of a Checkbox to a fully custom component.
It returns props to be placed on the custom component, along with fields representing the component's internal state.
Accessibility
Ensure the checkbox has an accessible name via a label element.
<Checkbox id="my-checkbox">
<Checkbox.Indicator />
</Checkbox>
<label htmlFor="my-checkbox">
My label
</label>