Blocks / Form renderer

Form renderer

A form schema as the form a respondent fills in: sections as pages, progress, messages, conditional questions, a review step.

import { FormRenderer, FormQuestionField, validateFormAnswers, cleanFormAnswers, formVisibility, formPages, parseFormAnswer, formAnswerText } from "@forgeron/ui";
/01 → Survey

Customer survey

Help us improve. It takes about two minutes.

Page 1 of 2

Your experience

How likely are you to recommend us to a colleague? (required)
How likely are you to recommend us to a colleague?
Overall, how would you rate the product?
How satisfied are you with each part? (required)
PoorFairGood
Speed
Documentation
Support
import { FormRenderer, type FormSchema } from "@forgeron/ui";

const schema: FormSchema = {
  version: 1,
  title: "Customer survey",
  description: "Help us improve. It takes about two minutes.",
  thanks: "Thank you. Your answers help us decide what to build next.",
  sections: [
    {
      id: "s1",
      title: "Your experience",
      questions: [
        {
          id: "nps",
          type: "scale",
          title: "How likely are you to recommend us to a colleague?",
          required: true,
          range: { min: 0, max: 10, nps: true, lowLabel: "Not likely", highLabel: "Very likely" },
        },
        {
          id: "stars",
          type: "rating",
          title: "Overall, how would you rate the product?",
          range: { min: 1, max: 5 },
        },
        {
          id: "grid",
          type: "matrix",
          title: "How satisfied are you with each part?",
          required: true,
          options: [
            { id: "speed", label: "Speed" },
            { id: "docs", label: "Documentation" },
            { id: "support", label: "Support" },
          ],
          columns: [
            { id: "low", label: "Poor" },
            { id: "mid", label: "Fair" },
            { id: "high", label: "Good" },
          ],
        },
      ],
    },
    {
      id: "s2",
      title: "What next",
      questions: [
        {
          id: "rank",
          type: "ranking",
          title: "Put these in the order you want them",
          options: [
            { id: "api", label: "A public API" },
            { id: "mobile", label: "A mobile app" },
            { id: "sso", label: "Single sign-on" },
          ],
        },
        { id: "more", type: "longText", title: "Anything else?", placeholder: "Optional" },
      ],
    },
  ],
};

export default function Survey() {
  return <FormRenderer schema={schema} />;
}
/02 → Intake

Access request

Page 1 of 2

Who needs access

Who is it for? (required)
import { FormRenderer, type FormAnswers, type FormSchema } from "@forgeron/ui";
import { useState } from "react";

// A request form: the second page only exists for some answers, and a follow-up question appears
// inside it. The review step lists the answers before they are sent.
const schema: FormSchema = {
  version: 1,
  title: "Access request",
  submitLabel: "Send request",
  thanks: "Request sent. You will hear back within two working days.",
  sections: [
    {
      id: "s1",
      title: "Who needs access",
      questions: [
        { id: "name", type: "shortText", title: "Full name", required: true },
        {
          id: "email",
          type: "shortText",
          title: "Work email",
          required: true,
          validation: { format: "email" },
        },
        {
          id: "kind",
          type: "singleChoice",
          title: "Who is it for?",
          required: true,
          options: [
            { id: "me", label: "Me" },
            { id: "contractor", label: "A contractor" },
          ],
        },
      ],
    },
    {
      id: "s2",
      title: "The contractor",
      description: "We need a few details before we can grant access.",
      showIf: {
        id: "g1",
        combinator: "and",
        rules: [{ id: "r1", field: "kind", operator: "eq", value: "contractor" }],
      },
      questions: [
        { id: "company", type: "shortText", title: "Company", required: true },
        { id: "until", type: "date", title: "Access ends on", required: true },
        {
          id: "nda",
          type: "singleChoice",
          title: "Is an NDA signed?",
          required: true,
          options: [
            { id: "yes", label: "Yes" },
            { id: "no", label: "Not yet" },
          ],
        },
        {
          id: "ndawhy",
          type: "longText",
          title: "When will it be signed?",
          showIf: {
            id: "g2",
            combinator: "and",
            rules: [{ id: "r2", field: "nda", operator: "eq", value: "no" }],
          },
        },
      ],
    },
    {
      id: "s3",
      title: "What for",
      questions: [
        {
          id: "systems",
          type: "multiChoice",
          title: "Systems",
          required: true,
          options: [
            { id: "git", label: "Source code" },
            { id: "wiki", label: "Wiki" },
            { id: "ci", label: "Build pipeline" },
          ],
          validation: { minSelected: 1 },
        },
      ],
    },
  ],
};

export default function Intake() {
  const [sent, setSent] = useState<FormAnswers | null>(null);
  return (
    <div style={{ display: "grid", gap: 16 }}>
      <FormRenderer schema={schema} onSubmit={setSent} />
      {sent ? (
        <pre
          style={{
            margin: 0,
            padding: 12,
            maxWidth: 640,
            overflow: "auto",
            border: "1px solid var(--line)",
            background: "var(--bg-sunk)",
            font: "12px/18px var(--font-mono)",
          }}
          aria-label="What onSubmit received"
        >
          {JSON.stringify(sent, null, 2)}
        </pre>
      ) : null}
    </div>
  );
}
/03 → Single page

Event registration

0 of 5 answered

You

––––
Postal address

For the badge and the invoice.

Documents

Proof of employment
Drop files here, or.pdf, image/* · up to 4.8 MB
Sign the code of conduct (required)

Draw with a pointer. From the keyboard: Space puts the pen down or lifts it, the arrows move it, Backspace undoes. Or use the Type or Upload tab.

import { FormRenderer, type FormSchema } from "@forgeron/ui";

// `layout="single"`: every section on one page, a progress bar that counts answers.
const schema: FormSchema = {
  version: 1,
  title: "Event registration",
  sections: [
    {
      id: "s1",
      title: "You",
      questions: [
        { id: "name", type: "shortText", title: "Name", required: true },
        { id: "time", type: "time", title: "Arrival time" },
        {
          id: "address",
          type: "address",
          title: "Postal address",
          help: "For the badge and the invoice.",
        },
      ],
    },
    {
      id: "s2",
      title: "Documents",
      questions: [
        {
          id: "files",
          type: "file",
          title: "Proof of employment",
          validation: { maxFiles: 2, maxSizeMb: 5, accept: ".pdf,image/*" },
        },
        { id: "sign", type: "signature", title: "Sign the code of conduct", required: true },
      ],
    },
  ],
};

const countries = [
  { value: "fr", label: "France" },
  { value: "be", label: "Belgium" },
  { value: "ch", label: "Switzerland" },
];

export default function SinglePage() {
  return <FormRenderer schema={schema} layout="single" countries={countries} />;
}
/04 → Quiz

Safety quiz

Where is the meeting point in case of fire? (required)
Which of these are fire exits? (required)
How many minutes until the alarm test? (required)
import { FormRenderer, type FormAnswers, type FormSchema } from "@forgeron/ui";
import { useState } from "react";

// A quiz is a form plus an answer key. The key stays outside the schema, on your side; the
// renderer hands back typed answers and you score them.
const schema: FormSchema = {
  version: 1,
  title: "Safety quiz",
  submitLabel: "Check my answers",
  thanks: "Done.",
  sections: [
    {
      id: "s1",
      title: "",
      questions: [
        {
          id: "q1",
          type: "singleChoice",
          title: "Where is the meeting point in case of fire?",
          required: true,
          options: [
            { id: "a", label: "The car park" },
            { id: "b", label: "The loading dock" },
            { id: "c", label: "The main lobby" },
          ],
        },
        {
          id: "q2",
          type: "multiChoice",
          title: "Which of these are fire exits?",
          required: true,
          options: [
            { id: "a", label: "The east stairs" },
            { id: "b", label: "The lift" },
            { id: "c", label: "The west stairs" },
          ],
        },
        {
          id: "q3",
          type: "number",
          title: "How many minutes until the alarm test?",
          required: true,
        },
      ],
    },
  ],
};

const key: Record<string, unknown> = { q1: "a", q2: ["a", "c"], q3: 15 };

const same = (a: unknown, b: unknown) =>
  JSON.stringify(Array.isArray(a) ? [...a].sort() : a) ===
  JSON.stringify(Array.isArray(b) ? [...b].sort() : b);

export default function Quiz() {
  const [score, setScore] = useState<string | null>(null);
  const grade = (answers: FormAnswers) => {
    const right = Object.keys(key).filter((id) => same(answers[id], key[id])).length;
    setScore(`${right} of ${Object.keys(key).length} right`);
  };
  return (
    <div style={{ display: "grid", gap: 12 }}>
      <FormRenderer schema={schema} onSubmit={grade} thanks={score ?? "Done."} />
    </div>
  );
}
API → Props
PropTypeDefaultDescription
schemaFormSchema—{ version: 1, title, description?, sections: { id, title, description?, showIf?, questions: FormQuestion[] }[], submitLabel?, thanks? }. Plain data: store it as JSON.
value / defaultValueFormAnswers—The answers by question id: text as a string, a choice as an option id, a number, a list of ids, a matrix as { rowId: columnId }, an address, files, a signature. Controlled or not.
onChange(answers: FormAnswers) => void—After every answer.
onSubmit(answers: FormAnswers) => void | Promise<void>—Called once the form is complete, with the answers of the questions shown, trimmed, hidden ones left out. The thanks screen shows when it resolves.
layout"pages" | "single""pages"One section at a time with a progress bar, or every section on one page.
reviewboolean—A last step that lists the answers, each page with an Edit button. On when there is more than one page.
page / defaultPage / onPageChangenumber—The step shown, from 0; the review comes after the last page.
countries{ value, label }[]—Countries offered by address questions.
showTitlebooleantrueThe title and description above the first page.
headingLevel1 | 2 | 32The level of the title; pages are one lower.
submittedboolean—Shows the thanks screen; controlled when given.
thanksReactNode—In place of `schema.thanks`.
disabledboolean—Locks every control.
classNamestring—Extra classes.