Checkbox

Capture boolean input from user
Import

Usage

Use Checkbox to capture boolean value input from user. For better accessibility set label prop, it will add associated label element.

Size
Color
<Checkbox
label="I agree to sell my privacy"
/>

Sizes

Checkbox has 5 predefined sizes: xs, sm, md, lg, xl. Size defines label font-size (from theme.fontSizes), input width and height:

<Checkbox size="xl" /> // -> predefined xl size

You can get checkbox sizes by importing CHECKBOX_SIZES:

import { CHECKBOX_SIZES } from '@mantine/core';
Prop valueWidth and height
xs12px
sm16px
md20px
lg26px
xl36px

Indeterminate state

Checkbox supports indeterminate state. When indeterminate prop is set to true, checked prop is ignored:

import React from 'react';
import { useListState, randomId } from '@mantine/hooks';
import { useMantineTheme, Checkbox } from '@mantine/core';
const initialValues = [
{ label: 'Receive email notifications', checked: false, key: randomId() },
{ label: 'Receive sms notifications', checked: false, key: randomId() },
{ label: 'Receive push notifications', checked: false, key: randomId() },
];
export function IndeterminateCheckbox() {
const theme = useMantineTheme();
const [values, handlers] = useListState(initialValues);
const allChecked = values.every((value) => value.checked);
const indeterminate = values.some((value) => value.checked) && !allChecked;
const items = values.map((value, index) => (
<Checkbox
style={{ marginTop: theme.spacing.xs, marginLeft: 33 }}
label={value.label}
key={value.key}
checked={value.checked}
onChange={(event) => handlers.setItemProp(index, 'checked', event.currentTarget.checked)}
/>
));
return (
<div>
<Checkbox
checked={allChecked}
indeterminate={indeterminate}
label="Receive all notifications"
onChange={() =>
handlers.setState((current) =>
current.map((value) => ({ ...value, checked: !allChecked }))
)
}
/>
{items}
</div>
);
}

Controlled

import React, { useState } from 'react';
import { Checkbox } from '@mantine/core';
function Demo() {
const [checked, setChecked] = useState(false);
return (
<Checkbox checked={checked} onChange={(event) => setChecked(event.currentTarget.checked)} />
);
}

Get element ref

You can get input ref by setting elementRef prop:

import React, { useRef } from 'react';
import { Checkbox } from '@mantine/core';
function Demo() {
const ref = useRef();
return <Checkbox elementRef={ref} />;
}

Accessibility

Provide aria-label in case you use checkbox without label for screen reader support:

<Checkbox label="My checkbox" />; // -> ok, input and label is connected
<Checkbox />; // not ok, input is not labeled
<Checkbox aria-label="My checkbox" />; // -> ok, label is not visible but will be announced by screen reader