Skip to content
Components, switch product

Checkbox group

<gui-checkbox-group> is a group of checkboxes to pick any number of options out of a few. It renders native checkboxes inside an element with the group role, named by the label. Its value is the list of the checked options’ values.

Code of the example above
CheckboxGroupBasic.tsx
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const toppings = ['Cheese', 'Ham', 'Olives', 'Mushrooms'];
export function CheckboxGroupBasic() {
return <GuiCheckboxGroup label="Toppings" options={toppings} />;
}

The element’s entry point is @golemui/gui-components/checkbox-group, which registers <gui-checkbox-group> and nothing else. To install the package and load the stylesheet, see Installation.

The @golemui/gui-components/react components have typed props and an on* prop for each event. React 18 or later.

ToppingsField.tsx
import { useState } from 'react';
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const choices = ['Cheese', 'Ham', 'Olives'];
export function ToppingsField() {
const [toppings, setToppings] = useState([] as string[]);
return (
<GuiCheckboxGroup
label="Toppings"
name="toppings"
options={choices}
values={toppings}
onGuiChange={(event) => setToppings(event.detail.value ?? [] as string[])}
/>
);
}

In HTML, options and values can also be JSON attributes, as in the examples below.

Properties

Property Type Default Description
localeId attribute locale-id string 'en' BCP 47 locale for formatting and parsing, such as en-US or es.
values OptionValue[] – The values of the checked options, in the options' order.
options OptionInput[] [] The options: values, which are both the text and the value, { label, value } objects, or any objects read through label-field and value-field.
labelField attribute label-field string – For options given as objects, the key of the text to show.
valueField attribute value-field string – For options given as objects, the key of the value.
direction 'row' | 'column' 'column' Lays the options out in a row or a column.
uid string – The id of the element's control. The ids of its label, hint and errors derive from it. Optional: when it is not set, the element generates one from its tag name and a page-wide counter, e.g. gui-textinput-3. Generated ids depend on creation order, so a server-rendered element must set uid or its ids will not match after hydration.
idPrefix attribute id-prefix string – Goes in front of every DOM id the element renders, so two elements with the same uid in different forms render different ids. GolemUI Forms sets it to the form's formName. Only ids and the references to them (for, aria-describedby…) take it: data-cy attributes and event details keep the bare uid.
domId read-only, no attribute string – The id of the element's control: uid, behind idPrefix when it is set.

Form control properties

Every field has these, from the base class of the form controls.

Property Type Default Description
value property only unknown – values, under the name every form control takes its value by.
name string – The name the value is submitted under. Without it the element stays out of its form. Reflected, like a native control's: the form reads a single value's name from the attribute.
label string – The visible label, which also names the control for assistive technology. Without one the control has no accessible name; the date, time, range, tags and file fields warn about it in development builds.
hint string – Help text shown under the label and announced as the control's description.
errors string[] [] Error messages to show, typically from your own validation. They show as soon as they are set, unless touched is false.
touched boolean – Whether the user has interacted with the control. Leave it unset unless you validate on interaction: false holds errors back until it becomes true.
required boolean false The control needs a value: it is marked as required and, with a name, blocks submission.
readOnly attribute readonly boolean – The value can be read and focused but not changed.
disabled boolean – Disabled by its own attribute or by a disabled <fieldset> around it. Setting the property sets the attribute, like a native control's.
form read-only, no attribute HTMLFormElement | null – The <form> the element belongs to, if any.
validity read-only, no attribute ValidityState – The element's validity, like a native control's.
validationMessage read-only, no attribute string – The message the browser shows for an invalid value.

Methods

Method Description
checkValidity(): boolean –
reportValidity(): boolean –

Events

Every event bubbles and is composed, so you can listen on any ancestor.

Event Description
gui-input The user checked or unchecked an option. detail.value is the new value.
gui-change The user committed the value. detail.value is the committed value.
gui-blur Focus left the group.

options takes the list of options. As an attribute it is a JSON array; from JavaScript, set the options property to an array. Each option is a string or a number, which is both its text and its value, as above, or a { label, value } object, to show a text other than the value.

values lists the values of the checked options. Leave it unset to start with none checked. The element keeps it in the options’ order, whatever order the user checks them in. The value property is the same list, under the name every form control reads its value by.

Code of the example above
CheckboxGroupObjects.tsx
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const channels = [
{ label: 'Email', value: 'email' },
{ label: 'Text message', value: 'sms' },
{ label: 'Push notification', value: 'push' },
];
export function CheckboxGroupObjects() {
return (
<GuiCheckboxGroup
label="Notify me by"
values={['email', 'push']}
options={channels}
/>
);
}

A value that matches no option checks nothing, and the element keeps it, after the options’ values. The user can’t see or change it.

When your options are objects with other keys, such as records from an API, label-field names the key of the text and value-field the key of the value. You don’t need to map them first. These two win over the objects’ own label and value keys.

Code of the example above
CheckboxGroupFields.tsx
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const languages = [
{ name: 'English', code: 'en' },
{ name: 'Spanish', code: 'es' },
{ name: 'Japanese', code: 'ja' },
];
export function CheckboxGroupFields() {
return (
<GuiCheckboxGroup
label="Subtitle languages"
labelField="name"
valueField="code"
options={languages}
/>
);
}

The options stack in a column. direction="row" lays them out side by side, and wraps them onto more lines when they don’t fit.

Code of the example above
CheckboxGroupRow.tsx
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
export function CheckboxGroupRow() {
return (
<GuiCheckboxGroup
label="Delivery days"
direction="row"
values={['Mon', 'Wed']}
options={days}
/>
);
}

A disabled group can’t be focused or changed, and a form doesn’t submit it. A readonly group can be focused, but clicks and Space don’t change it, and a form submits its values.

Code of the example above
CheckboxGroupDisabledReadonly.tsx
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
export function CheckboxGroupDisabledReadonly() {
return (
<div className="gui-grid gui-grid--row">
<div className="gui-grid__cell">
<GuiCheckboxGroup
label="Included in your plan"
values={['Backups']}
options={['Backups', 'Analytics']}
disabled
/>
</div>
<div className="gui-grid__cell">
<GuiCheckboxGroup
label="Roles"
values={['Editor']}
options={['Viewer', 'Editor']}
readOnly
/>
</div>
</div>
);
}

errors takes a list of messages from your own validation, and shows them under the group. Set the errors property from a gui-change listener to validate as the user works, such as a limit on how many options they pick. Check a third option.

Code of the example above
CheckboxGroupValidation.tsx
import { useState } from 'react';
import type { OptionValue } from '@golemui/gui-components';
import { GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const topics = ['Design', 'Engineering', 'Marketing', 'Sales'];
export function CheckboxGroupValidation() {
const [values, setValues] = useState<OptionValue[]>([]);
const errors = values.length > 2 ? ['Pick at most two interests.'] : [];
return (
<GuiCheckboxGroup
id="interests"
label="Interests"
hint="Pick up to two."
options={topics}
values={values}
errors={errors}
onGuiChange={(event) => setValues(event.detail.value ?? [])}
/>
);
}

With a name, <gui-checkbox-group> submits one entry per checked option under that name, like native checkboxes that share a name, so read them with FormData.getAll(). It submits nothing while none is checked. required blocks the submit until the user checks at least one. Submit the form below, then check two options and submit again.

Code of the example above
CheckboxGroupNativeForm.tsx
import { useState, type SubmitEvent } from 'react';
import { GuiButton, GuiCheckboxGroup } from '@golemui/gui-components/react';
import '@golemui/gui-components/index.css';
const toppings = [
{ label: 'Cheese', value: 'cheese' },
{ label: 'Ham', value: 'ham' },
{ label: 'Olives', value: 'olives' },
];
export function CheckboxGroupNativeForm() {
const [result, setResult] = useState('');
const onSubmit = (event: SubmitEvent<HTMLFormElement>) => {
event.preventDefault();
// getAll: the group submits one entry per checked option.
const checked = new FormData(event.currentTarget).getAll('toppings');
setResult(`Submitted ${JSON.stringify({ toppings: checked })}`);
};
return (
<form id="pizza" onSubmit={onSubmit}>
<div className="gui-grid">
<div className="gui-grid__cell">
<GuiCheckboxGroup
label="Toppings"
name="toppings"
required
options={toppings}
/>
</div>
<div className="gui-grid__cell">
<GuiButton type="submit" label="Order" />
</div>
</div>
<p id="pizza-result" role="status">
{result}
</p>
</form>
);
}

The checkboxes inside stay out of the form: the element submits the values itself.

How the elements submit, validate and reset is in Native forms.

<gui-checkbox-group> renders into the light DOM, so you can style every part with plain CSS. These are the parts and their public classes:

gui-checkbox-group
<gui-checkbox-group class="gui-field">
<span class="gui-label" id="toppings_label">
<span class="gui-label__text">
Toppings<span aria-hidden="true"> *</span>
</span>
<div class="gui-widget-hint" id="toppings_hint" aria-hidden="true">
Pick any you like.
</div>
</span>
<div
role="group"
class="gui-widget"
id="toppings"
aria-labelledby="toppings_label toppings_required"
aria-describedby="toppings_hint"
>
<span class="gui-visually-hidden" id="toppings_required">required</span>
<label for="toppings_0">
<input
type="checkbox"
id="toppings_0"
data-group="toppings"
form="toppings_none"
value="cheese"
aria-describedby="toppings_hint"
aria-invalid="true"
aria-errormessage="toppings_errors"
/>
Cheese
</label>
<label for="toppings_1">
<input
type="checkbox"
id="toppings_1"
data-group="toppings"
form="toppings_none"
value="ham"
aria-describedby="toppings_hint"
aria-invalid="true"
aria-errormessage="toppings_errors"
/>
Ham
</label>
<!-- One label and checkbox per option. -->
</div>
<div class="gui-validator" id="toppings_errors" role="alert">
<div class="gui-validator__error">Pick a topping.</div>
</div>
</gui-checkbox-group>
ClassPart
gui-fieldThe element itself. Lines its parts up with the fields next to it in a gui-grid row.
gui-labelThe group’s label, with the text and the hint.
gui-label__textThe label text and the required marker.
gui-widget-hintThe hint.
gui-widgetThe group, with a <label> and a checkbox per option.
gui-widget--horizontalOn the group with direction="row": lays the options out in a row.
gui-validatorThe errors container. It is always there, so the alert role announces new errors.
gui-validator__errorOne error message.

The options have no class of their own: select them as gui-checkbox-group label and gui-checkbox-group input. The ids derive from uid, or from a generated id such as gui-checkbox-group-3 when you don’t set one. Select by class or by tag, not by id.

The group draws its checkboxes as <gui-checkbox> does, and reads the same --gui-checkbox-* tokens, so one setting styles both. Set them on :root to change every checkbox, or on any element to change the checkboxes inside it:

TokenWhat it styles
--gui-checkbox-sizeThe width and height of each box. Defaults to 1rem.
--gui-checkbox-radiusThe boxes’ corner radius. Defaults to --gui-radius-sm.
--gui-checkbox-bgThe boxes’ background. Defaults to --gui-bg-surface.
--gui-checkbox-borderThe boxes’ border. Defaults to --gui-border-strong.
--gui-checkbox-tickThe tick. Defaults to --gui-intent-primary.
--gui-checkbox-gapThe space between a box and its text. Defaults to --gui-space-2.
--gui-text-defaultThe label and the options’ text.
--gui-font-familyThe font.
--gui-font-smThe text size of the label and the options.
--gui-font-xsThe text size of the hint and the errors.
--gui-text-secondaryThe hint.
--gui-border-focusThe border of the focused box.
--gui-shadow-focusThe focus ring.
--gui-intent-errorThe boxes’ border and the messages when there are errors.
--gui-shadow-focus-errorThe focus ring when there are errors.
styles.css
/* Bigger boxes, with more room before their text, in every checkbox. */
:root {
--gui-checkbox-size: 1.25rem;
--gui-checkbox-gap: 0.75rem;
}

To restyle beyond the tokens, see Overriding styles; for dark mode and the Clay theme, see Themes and dark mode.

  • Group. The checkboxes sit in an element with the group role, named by the label through aria-labelledby. Without a label the group has no accessible name. Each checkbox is named by its option’s text.
  • Description. The hint is the group’s description, through aria-describedby.
  • Errors. While errors show, the checkboxes have aria-invalid="true" and point at them with aria-errormessage, and screen readers announce new errors as they appear.
  • Required. A group has no required state of its own, and aria-required on a checkbox would mean that box must be checked. A required group adds “required” to its name instead, in a text hidden on screen. Translate it with the requiredGroup message, see i18n.
  • Read-only. readonly sets aria-readonly on each checkbox. They stay in the tab order.
  • Tab stops. Each checkbox is a stop in the tab order, as native checkboxes are. gui-blur fires only when focus leaves the group: moving from one checkbox to another doesn’t fire it.
KeyAction
TabMoves focus to the next checkbox, and out of the group.
SpaceChecks or unchecks the focused one, and fires gui-change.

In a read-only group Space does nothing.

What every element shares, such as translating the browser messages, is in Accessibility.