Utilities / getCollectionProps

getCollectionProps

A helper that returns all the props required to make a group of checkboxes or radio buttons accessible.

1const collectionProps = getCollectionProps(meta, options);

#Example

1import { useForm, getCollectionProps } from '@conform-to/react';
2
3function Example() {
4  const [form, fields] = useForm();
5
6  return (
7    <>
8      {getCollectionProps(fields.color, {
9        type: 'radio',
10        options: ['red', 'green', 'blue'],
11      }).map((props) => (
12        <label key={props.id} htmlFor={props.id}>
13          <input {...props} />
14          <span>{props.value}</span>
15        </label>
16      ))}
17    </>
18  );
19}

#Options

type

The type of the collection. It could be checkbox or radio.

options

The options of the collection. Each option will be treated as the value of the input and used to derive the corresponding key or id.

value

The helper will return a defaultValue unless this is set to false, e.g. a controlled input.

ariaAttributes

Decide whether to include aria-invalid and aria-describedby in the result props. Default to true.

ariaInvalid

Decide whether the aria attributes should be based on meta.errors or meta.allErrors. Default to errors.

ariaDescribedBy

Append additional id to the aria-describedby attribute. You can pass meta.descriptionId from the field metadata.

#Tips

The helper is optional

The helper is just a convenience function to help reducing boilerplate and make it more readable. You can always use the field metadata directly to set the props of your checkbox element.

1// Before
2function Example() {
3  return (
4    <form>
5      {['a', 'b', 'c'].map((value) => (
6        <label key={value} htmlFor={`${fields.category.id}-${value}`}>
7          <input
8            type="checkbox"
9            key={`${fields.category.key}-${value}`}
10            id={`${fields.category.id}-${value}`}
11            name={fields.category.name}
12            form={fields.category.formId}
13            value={value}
14            defaultChecked={fields.category.initialValue?.includes(value)}
15            aria-invalid={!fields.category.valid || undefined}
16            aria-describedby={
17              !fields.category.valid ? fields.category.errorId : undefined
18            }
19          />
20          <span>{value}</span>
21        </label>
22      ))}
23      x
24    </form>
25  );
26}
27
28// After
29function Example() {
30  return (
31    <form>
32      {getCollectionProps(fields.category, {
33        type: 'checkbox',
34        options: ['a', 'b', 'c'],
35      }).map((props) => (
36        <label key={props.id} htmlFor={props.id}>
37          <input {...props} />
38          <span>{props.value}</span>
39        </label>
40      ))}
41    </form>
42  );
43}

Make your own helper

The helper is designed for the native checkbox elements. If you need to use a custom component, you can always make your own helpers.