Skip to content

Commit

Permalink
docs: enable multiple-type toggle-group in shadcn-ui examples (#753)
Browse files Browse the repository at this point in the history
  • Loading branch information
pwli0755 authored Sep 10, 2024
1 parent c0c3195 commit a0e422f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
17 changes: 17 additions & 0 deletions examples/shadcn-ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const UserSubscriptionSchema = z.object({
accountType: z.enum(['personal', 'business'], {
required_error: 'You must select an account type',
}),
accountTypes: z.array(z.enum(['personal', 'business'])).min(1,'You must select at least one account type'),
interests: z
.array(z.string())
.min(3, 'You must select at least three interest'),
Expand Down Expand Up @@ -164,6 +165,22 @@ function App() {
<FieldError>{fields.accountType.errors}</FieldError>
)}
</Field>
<Field>
<Label htmlFor={fields.accountTypes.id}>Account types</Label>
<ToggleGroupConform
type="multiple"
meta={fields.accountTypes}
items={[
{ value: 'personal', label: 'Personal' },
{ value: 'business', label: 'Business' },
{ value: 'business2', label: 'Business2' },
]}
/>
{fields.accountTypes.allErrors && (
<FieldError>{
Object.values(fields.accountTypes.allErrors).flat()}</FieldError>
)}
</Field>
<Field>
<fieldset>Interests</fieldset>
<CheckboxGroupConform
Expand Down
28 changes: 24 additions & 4 deletions examples/shadcn-ui/src/components/conform/ToggleGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,20 @@ import { ComponentProps, ElementRef, useRef } from 'react';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';

export const ToggleGroupConform = ({
type = 'single',
meta,
items,
...props
}: {
items: Array<{ value: string; label: string }>;
meta: FieldMetadata<string>;
meta: FieldMetadata<string | string[]>;
} & Omit<ComponentProps<typeof ToggleGroup>, 'defaultValue'>) => {
const toggleGroupRef = useRef<ElementRef<typeof ToggleGroup>>(null);
const control = useControl(meta);
const control = useControl<string | string[]>(meta);

return (
<>
<input
{type === 'single' ? <input
name={meta.name}
ref={control.register}
className="sr-only"
Expand All @@ -27,9 +28,28 @@ export const ToggleGroupConform = ({
onFocus={() => {
toggleGroupRef.current?.focus();
}}
/>
/> : <select
multiple
name={meta.name}
className="sr-only"
ref={control.register}
onFocus={() => {
toggleGroupRef.current?.focus();
}}
defaultValue={meta.initialValue}
tabIndex={-1}
>
{items.map((item) => (
<option value={item.value} key={item.value}>
{item.label}
</option>
))}
</select>
}

<ToggleGroup
{...props}
type={type}
ref={toggleGroupRef}
value={control.value}
onValueChange={(value) => {
Expand Down

0 comments on commit a0e422f

Please sign in to comment.