Skip to content
Open Cloud

shadcn/ui ​

Map shadcn/ui components to Formhaus field types through the components prop of FormRenderer.

Open in StackBlitz · Source

Setup ​

The example is a Vite project with Tailwind CSS v4, created by the shadcn CLI with the Base UI primitives:

bash
pnpm dlx shadcn@latest init --template vite --base base --preset nova
pnpm dlx shadcn@latest add input select checkbox radio-group button label card textarea
pnpm add @formhaus/core @formhaus/react

Component map ​

mapControls maps one shadcn/ui control per field type. Types without an entry fall back to the built-in HTML fields.

tsx
import type { FieldComponentMap } from '@formhaus/react';
import { mapControls } from '@formhaus/react/controls';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { RadioGroup } from '@/components/ui/radio-group';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { AutocompleteInput } from './fields/AutocompleteInput';
import { CheckboxList, native, points, radios, stars } from './fields/choices';
import { FileInput } from './fields/FileInput';
import { MatrixRow } from './fields/MatrixRow';
import { SelectControl } from './fields/SelectControl';
import { Shell } from './fields/Shell';

export const components: FieldComponentMap = mapControls({
  shell: Shell,
  matrix: MatrixRow,
  freeText: true,
  conditionalReveal: ['radio', 'multiselect'],
  controls: {
    input: Input,
    textarea: Textarea,
    select: { component: SelectControl, optionsProp: 'options' },
    autocomplete: { component: AutocompleteInput, optionsProp: 'options' },
    multiselect: { component: CheckboxList, props: (f, options) => ({ f, options }) },
    checkbox: { component: Checkbox, props: native, changeProp: 'onCheckedChange' },
    switch: { component: Switch, props: native, changeProp: 'onCheckedChange' },
    radio: { component: RadioGroup, props: radios, changeProp: 'onValueChange' },
    scale: { component: RadioGroup, props: points, changeProp: 'onValueChange' },
    rating: { component: RadioGroup, props: stars, changeProp: 'onValueChange' },
    file: { component: FileInput, props: (f, _, { field }) => ({ f, field }) },
  },
});

Shell ​

One shell renders the label, the helper, the error and the required mark for every control:

tsx
import type { ControlShellProps } from '@formhaus/react/controls';
import { Field, FieldDescription, FieldError, FieldLabel, FieldLegend, FieldSet } from '@/components/ui/field';
import { cn } from '@/lib/utils';

export function RequiredMark({ f }: Pick<ControlShellProps, 'f'>) {
  return f.required ? (
    <span aria-hidden="true" className="text-destructive">
      {' *'}
    </span>
  ) : null;
}

export function Shell({ kind, field, f, rootProps, anchors, children }: ControlShellProps) {
  const text = (
    <span>
      {f.label}
      <RequiredMark f={f} />
    </span>
  );
  const texts = (
    <>
      {anchors.some(Boolean) && (
        <div className="flex justify-between text-xs text-muted-foreground">
          {anchors.map((anchor, index) => (
            <span key={index}>{anchor?.label}</span>
          ))}
        </div>
      )}
      {f.helperText && <FieldDescription id={f.helperId}>{f.helperText}</FieldDescription>}
      {f.error && <FieldError id={f.errorId}>{f.error}</FieldError>}
    </>
  );
  if (kind === 'group')
    return (
      <FieldSet
        {...rootProps}
        data-invalid={f.invalid || undefined}
        className={cn(
          'gap-2',
          field.layout === 'inline' &&
            '*:data-[slot=radio-group]:flex *:data-[slot=radio-group]:flex-wrap *:data-[slot=radio-group]:gap-x-6',
        )}
      >
        <FieldLegend variant="label" className={cn('mb-2', f.invalid && 'text-destructive')}>
          {text}
        </FieldLegend>
        {children}
        {texts}
      </FieldSet>
    );
  return (
    <Field {...rootProps} data-invalid={f.invalid || undefined}>
      {kind === 'input' ? (
        <>
          <FieldLabel htmlFor={f.id}>{text}</FieldLabel>
          {children}
        </>
      ) : (
        <div className="flex items-center gap-2">
          {children}
          <FieldLabel htmlFor={f.id} className="font-normal">
            {text}
          </FieldLabel>
        </div>
      )}
      {texts}
    </Field>
  );
}

Choices ​

Radio, scale, rating and multiselect options, with image tiles when the options have images:

tsx
import { Radio } from '@base-ui/react/radio';
import { toggleOption } from '@formhaus/core/fields';
import type { FieldProps } from '@formhaus/react';
import type { ControlOption } from '@formhaus/react/controls';
import { Star } from 'lucide-react';
import { Fragment } from 'react';
import { buttonVariants } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { RadioGroupItem } from '@/components/ui/radio-group';
import { cn } from '@/lib/utils';

export const native = () => ({ nativeButton: true, render: <button type="button" /> });

function Reveal({ reveal }: Pick<ControlOption, 'reveal'>) {
  return reveal ? (
    <div
      id={reveal.id}
      data-fh="reveal"
      role="group"
      hidden={!reveal.open}
      className="ml-1.5 grid gap-5 border-l-2 pl-4"
      onKeyDown={(event) => event.stopPropagation()}
    >
      {reveal.children}
    </div>
  ) : null;
}

interface CheckboxListProps {
  f: FieldProps;
  options: ControlOption[];
  value: unknown;
  onChange: (value: unknown) => void;
}

export function CheckboxList({ f, options, value, onChange }: CheckboxListProps) {
  return (
    <div className="grid gap-2">
      {options.map((option, index) => {
        const { checked, value: picked } = f.option({ ...option, value: String(option.value) }, index);
        return (
          <Fragment key={option.value}>
            <Label className="font-normal">
              <Checkbox
                checked={checked}
                onCheckedChange={() => onChange(toggleOption(value, picked))}
                aria-invalid={f.invalid || undefined}
                aria-controls={option.reveal?.id}
                aria-expanded={option.reveal?.open}
              />
              {option.label}
            </Label>
            <Reveal reveal={option.reveal} />
          </Fragment>
        );
      })}
    </div>
  );
}

const tile =
  'flex-col items-stretch gap-2 rounded-lg border p-2 font-normal has-[[data-checked]]:border-primary has-[[data-checked]]:ring-1 has-[[data-checked]]:ring-primary';

export const radios = (f: FieldProps, options: ControlOption[]) => {
  const tiles = options.some((option) => option.image);
  return {
    className: tiles ? 'grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-3' : undefined,
    children: options.map((option) =>
      tiles ? (
        <Label key={option.value} className={tile}>
          {option.image && <img src={option.image} alt="" className="aspect-[4/3] w-full rounded-md object-cover" />}
          <span className="flex items-center gap-2">
            <RadioGroupItem value={option.value} aria-invalid={f.invalid || undefined} />
            {option.label}
          </span>
        </Label>
      ) : (
        <Fragment key={option.value}>
          <Label className="font-normal">
            <RadioGroupItem value={option.value} aria-invalid={f.invalid || undefined} aria-controls={option.reveal?.id} />
            {option.label}
          </Label>
          <Reveal reveal={option.reveal} />
        </Fragment>
      ),
    ),
  };
};

export const points = (f: FieldProps, options: ControlOption[]) => ({
  className: 'gap-1.5',
  style: { gridTemplateColumns: `repeat(${Math.min(options.length, 6)}, minmax(0, 1fr))` },
  children: options.map((option) => (
    <Radio.Root
      key={option.value}
      value={option.value}
      aria-invalid={f.invalid || undefined}
      className={cn(buttonVariants({ variant: f.value === option.value ? 'default' : 'outline', size: 'lg' }))}
    >
      {option.label}
    </Radio.Root>
  )),
});

export const stars = (f: FieldProps, options: ControlOption[]) => ({
  className: 'flex gap-1',
  children: options.map((option) => (
    <Radio.Root
      key={option.value}
      value={option.value}
      aria-label={`${option.label} of ${options.length}`}
      aria-invalid={f.invalid || undefined}
      className={buttonVariants({ variant: 'ghost', size: 'icon' })}
    >
      <Star className={cn('size-6', Number(f.value) >= Number(option.value) ? 'fill-primary text-primary' : 'text-muted-foreground')} />
    </Radio.Root>
  )),
});

The Base UI Select takes the options as items, so SelectValue shows the option label instead of the stored value:

tsx
import type { ControlOption } from '@formhaus/react/controls';
import { type ComponentProps, useState } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

type SelectControlProps = Omit<ComponentProps<typeof SelectTrigger>, 'value' | 'onChange' | 'onBlur'> & {
  options: ControlOption[];
  value: string;
  name?: string;
  placeholder?: string;
  onChange: (value: unknown) => void;
  onBlur: () => void;
};

export function SelectControl({ options, value, name, placeholder, disabled, onChange, onBlur, ...trigger }: SelectControlProps) {
  const [open, setOpen] = useState(false);
  return (
    <Select
      items={options}
      value={value || null}
      name={name}
      disabled={disabled}
      open={open}
      onOpenChange={(next) => {
        setOpen(next);
        if (!next) onBlur();
      }}
      onValueChange={(next) => onChange(next ?? '')}
    >
      <SelectTrigger {...trigger} className="w-full" onBlur={() => !open && onBlur()}>
        <SelectValue placeholder={placeholder ?? 'Select...'} />
      </SelectTrigger>
      <SelectContent>
        {options.map((option) => (
          <SelectItem key={option.value} value={option.value}>
            {option.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

Next.js ​

The component map holds functions that cannot cross from a server component. Render FormRenderer with the map in a file that starts with 'use client', and import that file from the server component. See Next.js.

Actions and progress ​

tsx
import type { FormActionsProps } from '@formhaus/react';
import { Button } from '@/components/ui/button';

export function FormActions({ primaryLabel, showPrimary = true, showBack, backLabel, loading, onPrimary, onBack }: FormActionsProps) {
  return (
    <div className="flex justify-between gap-2 pt-2">
      {showBack ? (
        <Button type="button" variant="outline" disabled={loading} onClick={onBack}>
          {backLabel}
        </Button>
      ) : (
        <span />
      )}
      {showPrimary && (
        <Button type="button" disabled={loading} onClick={onPrimary}>
          {primaryLabel}
        </Button>
      )}
    </div>
  );
}
tsx
import type { FormStepProgressProps } from '@formhaus/react';

export function StepProgress({ counterLabel, stepTitle, stepDescription, stepErrorsLabel, headingLevel = 2 }: FormStepProgressProps) {
  const Heading = `h${headingLevel}` as const;

  return (
    <div className="grid gap-1 pb-2">
      <p className="text-sm text-muted-foreground">{counterLabel}</p>
      {stepTitle && <Heading className="text-lg font-medium">{stepTitle}</Heading>}
      {stepErrorsLabel && <p className="text-sm text-destructive">{stepErrorsLabel}</p>}
      {stepDescription && <p className="text-sm text-muted-foreground">{stepDescription}</p>}
    </div>
  );
}

App ​

tsx
import { parseDefinition, type FormDefinition } from '@formhaus/core';
import { FormRenderer } from '@formhaus/react';
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FormCompletion } from './FormCompletion';
import { components } from './component-map';
import json from './definition.json';
import { FormActions } from './FormActions';
import { ErrorSummary } from './ErrorSummary';
import { ConfirmDialog, Group, GroupItem } from './Groups';
import { Section } from './Section';
import { StepProgress } from './StepProgress';

const layout = {
  actions: FormActions,
  progress: StepProgress,
  section: Section,
  errorSummary: ErrorSummary,
  group: Group,
  groupItem: GroupItem,
  confirmDialog: ConfirmDialog,
};

const initial = parseDefinition(json);

export function App({ definition = initial }: { definition?: FormDefinition }) {
  const [submitted, setSubmitted] = useState<Record<string, unknown> | null>(null);

  return (
    <main className="mx-auto max-w-166 px-4 py-8">
      {submitted ? (
        <FormCompletion definition={definition} values={submitted} onRestart={() => setSubmitted(null)} />
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>{definition.title}</CardTitle>
          </CardHeader>
          <CardContent>
            <FormRenderer definition={definition} components={components} layout={layout} conditionalReveal onSubmit={setSubmitted} />
          </CardContent>
        </Card>
      )}
    </main>
  );
}

FormRenderer wraps fields in .fh-form and .fh-form__fields. Without @formhaus/core/style.css, add the spacing in your stylesheet:

css
@layer components {
  .fh-form,
  .fh-form__fields {
    @apply grid gap-5;
  }
}

Server validation ​

The example validates in the browser only. On the server, run validateSubmission() from @formhaus/core/server on the posted values and pass the returned errors to the errors prop. See Server-side validation and Next.js for a complete route handler.