wealth/packages/island/src/molecules/chip-group/ChipGroup.tsx

54 lines
1.4 KiB
TypeScript

import { useId } from 'react';
import { Chip } from '../../atoms/chip';
import { FieldError } from '../../atoms/field-error';
import { FlexBox } from '../../atoms/flex-box';
import type { ChipGroupProps } from './types';
/**
* A multiple choice as a wrapping row of toggle chips, such as markets, with its error under it.
* The fieldset is named and can take focus, so a form error can send the person to it.
*/
export function ChipGroup<T extends string>({
options,
value,
onToggle,
label,
error,
size = 'md',
disabled = false,
ref,
className,
}: ChipGroupProps<T>) {
const errorId = useId();
const hasError = error != null && error !== false;
return (
<FlexBox direction="flex-col" gap="gap-2" className={className}>
<FlexBox
ref={ref}
tag="fieldset"
tabIndex={-1}
aria-label={label}
aria-describedby={hasError ? errorId : undefined}
wrap="flex-wrap"
gap="gap-2"
className="rounded-md outline-none"
>
{options.map((option) => (
<Chip
key={option.value}
size={size}
selected={value.includes(option.value)}
disabled={disabled}
onClick={() => onToggle(option.value)}
>
{option.label}
</Chip>
))}
</FlexBox>
{hasError && <FieldError id={errorId}>{error}</FieldError>}
</FlexBox>
);
}