React Checkbox Pro

Checkbox Group

How to use the CheckboxGroup component for managing multiple checkboxes

Checkbox Group

Learn how to use the CheckboxGroup component to manage multiple related checkboxes.

Basic Example

Horizontal Layout

Label Placement

Props

PropTypeDefault
children
ReactNode
-
value
string[]
-
defaultValue
string[]
-
onChange
(value: string[]) => void
-
disabled
boolean
-
name
string
-
orientation
"horizontal" | "vertical"
-
spacing
"sm" | "md" | "lg"
-
labelPlacement
LabelPlacement
-
className
string
-
error
boolean
-
aria-label
string
-
aria-labelledby
string
-

Usage Examples

Controlled Group

function ControlledGroup() {
  const [selected, setSelected] = useState(['option1']);
 
  return (
    <CheckboxGroup
      value={selected}
      onChange={setSelected}
    >
      <Checkbox value="option1">Option 1</Checkbox>
      <Checkbox value="option2">Option 2</Checkbox>
    </CheckboxGroup>
  );
}

With Form Integration

function FormExample() {
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    console.log(formData.getAll('preferences'));
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <CheckboxGroup
        name="preferences"
        defaultValue={['email']}
      >
        <Checkbox value="email">Email Updates</Checkbox>
        <Checkbox value="newsletter">Newsletter</Checkbox>
      </CheckboxGroup>
      <button type="submit">Submit</button>
    </form>
  );
}

Best Practices

  1. Group Organization:

    • Group related options together
    • Use clear, descriptive labels
    • Consider using sections for large groups
  2. Layout:

    • Choose appropriate orientation
    • Use consistent spacing
    • Consider responsive design
  3. Accessibility:

    • Provide group labels
    • Use semantic HTML
    • Maintain keyboard navigation
  4. State Management:

    • Choose between controlled and uncontrolled
    • Handle state changes efficiently
    • Consider form integration needs

On this page