# Building the form UI – Form Builder

Render a form with React and React Hook Form: field mapping, pages, conditions and prefill.

The sample project renders a resolved form with React and [React Hook Form](https://react-hook-form.com). The code is in [`examples/form-builder-next`](https://github.com/san26786/geecon-contentful/tree/main/examples/form-builder-next), in `src/components/FormRenderer.tsx`. It's one component you can copy and restyle. It uses plain HTML elements, so it works with any styling.

Submitting in the sample validates the answers and logs them. Nothing is sent. Sending answers to your own backend is up to you.

## Set up the form

Start React Hook Form with the prefilled answers, and a resolver that builds the Zod schema from the current answers. That way a conditional field is checked only while it's shown. See [Validation with Zod](https://contentful.geeconglobal.com/apps/form-builder/docs/validation-with-zod).

```tsx title="examples/form-builder-next/src/components/FormRenderer.tsx (trimmed)"
const { register, watch, setValue, trigger, handleSubmit, formState: { errors } } = useForm<Values>({
  defaultValues: defaultValues(form, urlParams),
  resolver: (values, context, options) => zodResolver(toZodSchema(form, values))(values, context, options),
});
const values = watch();
const visible = (item: Item) => isVisible(item, values, allItems);
```

## Map field types to inputs

Each field type maps to an element. Text-like types share one `<input>` with a different `type`. Labels, placeholders, help and option labels come from the merged texts by key.

```tsx title="examples/form-builder-next/src/components/FormRenderer.tsx (trimmed)"
const INPUT_TYPES = {
  shortText: "text", email: "email", phone: "tel", url: "url", date: "date", time: "time", number: "text",
};

const text = (key: string) => (typeof texts[key] === "string" ? (texts[key] as string) : undefined);
const label = (id: string) => text(`${id}.label`) ?? id;

switch (f.type) {
  case "hidden":
    return <input type="hidden" {...register(f.id)} />;
  case "longText":
    return <textarea id={id} rows={4} autoComplete={autoComplete} {...register(f.id)} />;
  case "dropdown":
    return (
      <select id={id} autoComplete={autoComplete} {...register(f.id)}>
        <option value="">{text(`${f.id}.placeholder`) ?? "Choose an option"}</option>
        {(f.options ?? []).map((o) => (
          <option key={o} value={o}>{text(`${f.id}.options.${o}`) ?? o}</option>
        ))}
      </select>
    );
  // radio and checkboxes: one input per option, inside a fieldset with a legend
  // yesNo and consent: one checkbox. yesNo shows `<id>.on` or `<id>.off` next to it
  default:
    return <input id={id} type={INPUT_TYPES[f.type]} autoComplete={autoComplete} {...register(f.id)} />;
}
```

`autoComplete` is `f.autocomplete`, or `email`, `tel` and `url` for email, phone and web address fields when it's unset.

Texts for a field are looked up by key: `<fieldId>.label`, `.placeholder`, `.help`, `<fieldId>.options.<value>` and `<fieldId>.on` / `.off`. See [Data format](https://contentful.geeconglobal.com/apps/form-builder/docs/data-format).

## Layout items and conditions

Render only the items that `isVisible` allows. Headings and paragraphs take their text from `<itemId>.text`, and a divider is a rule.

```tsx title="examples/form-builder-next/src/components/FormRenderer.tsx (trimmed)"
function renderItem(item: Item): ReactNode {
  if (!visible(item)) return null;
  if (!isLayout(item)) return renderField(item);
  if (item.type === "divider") return <hr key={item.id} />;
  if (item.type === "heading") return <h2 key={item.id}>{text(`${item.id}.text`)}</h2>;
  return <RichText key={item.id} value={texts[`${item.id}.text`]} />;
}
```

## Pages

Show one page at a time. **Next** validates the visible fields of the current page before it moves on. If a submit fails on another page, go to the first page with an error.

```tsx title="examples/form-builder-next/src/components/FormRenderer.tsx (trimmed)"
async function next() {
  if (await trigger(pageFields(step).map((f) => f.id))) {
    movedPage.current = true; // an effect then focuses the new page's heading
    setStep(step + 1);
  } else setAttempts((n) => n + 1);
}
```

Page titles are in `page.<pageId>.title`, and the button texts in `form.next`, `form.back` and `form.submit`.

## Errors

After a failed attempt the sample shows an error summary (the `form.errorSummary.title` and `.body` texts, with a link to each field) and moves focus to it. Each field also gets `aria-invalid` and `aria-describedby`, which point at its help and error text.

## Accessibility checklist

The sample meets WCAG 2.2 AA. If you build your own UI, keep these:

- Every control has a visible `<label>`. Radio buttons and checkboxes sit in a `<fieldset>` whose `<legend>` is the field's label.
- Required fields show a `*`, and the form shows `form.requiredNote` above the fields to explain it. Inputs and radio groups (`role="radiogroup"`) carry `aria-required`, so the `*` is hidden from screen readers there. A checkbox group can't carry `aria-required`, so its `*` is left for screen readers to read out.
- Each field's `autocomplete` attribute comes from the definition (see [Map field types to inputs](#map-field-types-to-inputs)).
- Errors: an error summary that takes focus and links to each field, plus `aria-invalid` and `aria-describedby` on the field.
- On a multi-page form, **Next** and **Back** move focus to the new page's heading (`tabIndex={-1}`), so screen readers announce the page.
- After submit, focus moves to the message that replaces the form (`role="status"`, `tabIndex={-1}`).
- Mark the form with the language it's shown in, for example `<div lang="fr">`, when the page around it is in another language.
- Keep a visible focus outline, colour contrast of at least 4.5:1 for text, and a layout that works at 320 CSS px wide.

## Prefill

A field can be filled from the page address (`prefill.source` is `url`, and `key` is the query parameter) or from your site (`source` is `site`, and `key` is one of the keys an admin configured, such as `user.email`). The sample reads the URL itself and leaves the `site` source as a stub for you to connect to your own data.

```ts title="examples/form-builder-next/src/lib/form-builder/prefill.ts (trimmed)"
// Replace with your site's data (e.g. the signed-in user). Called for fields with `prefill.source === "site"`.
function siteValue(key: string): string | undefined {
  const user: Record<string, string> = {}; // e.g. { email: session.user.email }
  return user[key];
}

function initial(f: FormField, url: Record<string, string>): unknown {
  const prefilled = f.prefill?.source === "url" ? url[f.prefill.key] : f.prefill ? siteValue(f.prefill.key) : undefined;
  switch (f.type) {
    case "hidden":
      return prefilled ?? f.hiddenValue ?? "";
    case "dropdown":
    case "radio":
      return prefilled && f.options?.includes(prefilled) ? prefilled : "";
    // ...
    default:
      return prefilled ?? "";
  }
}
```

A prefilled value for a choice field is used only if it's one of the field's options. A hidden field starts with its `hiddenValue`, unless a prefill overrides it.

## Submit and after submit

On submit, send only the visible fields' answers, and leave out blank ones (only spaces counts as blank). Number answers are numbers.

```tsx title="examples/form-builder-next/src/components/FormRenderer.tsx (trimmed)"
const onValid = (data: Values) => {
  const payload: Values = {};
  for (const f of allItems) {
    const v = data[f.id];
    if (isLayout(f) || !visible(f) || (typeof v === "string" && v.trim() === "")) continue;
    payload[f.id] = f.type === "number" ? Number(data[f.id]) : data[f.id];
  }
  // Send `payload` to your own backend here.
};
```

Then follow `definition.afterSubmit`:

- `message`: show the rich text in `afterSubmit.message`.
- `url`: go to the address. Follow only `http` and `https` addresses.
- `entry`: the entry is a page on your site. Look it up with your own routing and go there.

`definition.customProperties` hold the key and value pairs an editor set on the form. Send them with the submission if your backend needs them.

## Closed and scheduled forms

Check `effectiveStatus` before you render the form, and show the `form.closed` text when it isn't `open`. See [Reading forms](https://contentful.geeconglobal.com/apps/form-builder/docs/reading-forms).
