GuidesReview step

Guides

Review step

Learn how to add a review step that lets users edit any previous answer before submitting.


Initial steps

We'll show you how to add a review step with edit buttons that jump back to each form. To follow along, start by cloning the repository below, which is our starting point.

Terminal
git clone https://github.com/martiserra99/formity-review-step

Then install the dependencies.

Terminal
npm install

The repo is a React project using Vite and TypeScript, with @formity/react already installed for you. It contains a job application form built with React Hook Form, with four steps and a review step.

Before we start

Before changing anything, let's look at the code we start from. There are four files that we'll update, and the rest of the repo stays as it is.

The first one is src/components/form/index.tsx, with the Form component.

TSX
// src/components/form/index.tsx
import type { DefaultValues, Resolver } from "react-hook-form";
import type { Back, Next } from "@formity/react";

import { useForm, FormProvider } from "react-hook-form";

import { ItemView, type Item } from "./item";
import { Button } from "../button";

interface FormProps<T extends Record<string, unknown>> {
  defaultValues: DefaultValues<T>;
  resolver: Resolver<T>;
  heading: string;
  message: string;
  content: Item[];
  buttons: {
    back: string | null;
    next: string;
  };
  back: Back<T>;
  next: Next<T>;
}

export function Form<T extends Record<string, unknown>>({
  defaultValues,
  resolver,
  heading,
  message,
  content,
  buttons,
  back,
  next,
}: FormProps<T>) {
  const form = useForm({ defaultValues, resolver });
  return (
    <div className="flex h-full w-full items-center justify-center overflow-y-auto bg-white px-4 py-12">
      <div className="w-full max-w-lg">
        <form noValidate autoComplete="off" onSubmit={form.handleSubmit(next)}>
          <FormProvider {...form}>
            <div className="mb-8">
              <h2 className="mb-1.5 text-2xl font-bold text-gray-950">
                {heading}
              </h2>
              <p className="text-sm font-medium text-gray-400">{message}</p>
            </div>
            <div className="mb-8 flex flex-col gap-6">
              {content.map((item, i) => (
                <ItemView key={i} {...item} />
              ))}
            </div>
            <div className="flex w-full items-center justify-end gap-4">
              {buttons.back && (
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => back(form.getValues())}
                >
                  {buttons.back}
                </Button>
              )}
              <Button type="submit" variant="primary">
                {buttons.next}
              </Button>
            </div>
          </FormProvider>
        </form>
      </div>
    </div>
  );
}

Each field in content is described by an Item object and rendered by the ItemView component. The status prop tells the form whether it's being submitted, through its submitting property.

The second one is src/components/review/index.tsx, with the Review component.

TSX
// src/components/review/index.tsx
import type { Next } from "@formity/react";
import type { FormStatus } from "../../types/status";

import { ItemView, type Item } from "./item";
import { Button } from "../button";

interface ReviewProps {
  heading: string;
  message: string;
  content: Item[];
  button: string;
  next: Next<Record<never, never>>;
  status: FormStatus;
}

export function Review({
  heading,
  message,
  content,
  button,
  next,
  status,
}: ReviewProps) {
  return (
    <div className="flex h-full w-full items-center justify-center overflow-y-auto bg-white px-4 py-12">
      <div className="w-full max-w-lg">
        <div className="mb-8">
          <h2 className="mb-1.5 text-2xl font-bold text-gray-950">{heading}</h2>
          <p className="text-sm font-medium text-gray-400">{message}</p>
        </div>
        <div className="mb-8 flex flex-col gap-4">
          {content.map((item, i) => (
            <ItemView key={i} item={item} onEdit={() => {}} />
          ))}
        </div>
        <div className="flex w-full items-center justify-end gap-4">
          <Button
            variant="primary"
            onClick={() => next({})}
            disabled={status.submitting}
          >
            {status.submitting ? "Submitting..." : button}
          </Button>
        </div>
      </div>
    </div>
  );
}

Each entry in content is an Item with a title, the rows to show, and the id of the form to be edited. Its ItemView renders an edit button that calls onEdit with that id.

The third one is src/flow.tsx, which contains the Schema and the flow.

TSX
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Form } from "./components/form";
import { Review } from "./components/review";

import * as constants from "./constants";
import * as format from "./utils/format";

type Values = UnionToIntersection<Fields[keyof Fields]>;

type Fields = {
  personal: {
    name: string;
    email: string;
  };
  background: {
    experience: string;
    jobTitle: string;
  };
  preferences: {
    employmentType: string;
    workArrangement: string;
  };
  about: {
    whyRole: string;
    greatestStrength: string;
  };
};

export type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<Fields["personal"]>,
    s.Form<Fields["background"]>,
    s.Form<Fields["preferences"]>,
    s.Form<Fields["about"]>,
    s.Form<Record<never, never>>,
    s.Return<Values>,
  ];
  inputs: Record<never, never>;
  params: {
    status: FormStatus;
  };
};

export const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({
        name: ["", []],
        email: ["", []],
      }),
      render: ({ fields, back, next }) => (
        <Form
          key="personal"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              name: z.string().nonempty("Please enter your full name"),
              email: z.email("Please enter a valid email address"),
            }),
          )}
          heading="Personal details"
          message="Let's start with your basic contact information."
          content={[
            {
              type: "input",
              name: "name",
              label: "Full name",
              placeholder: "Jane Smith",
            },
            {
              type: "input",
              name: "email",
              label: "Email address",
              placeholder: "jane@example.com",
            },
          ]}
          buttons={{
            back: null,
            next: "Continue",
          }}
          back={back}
          next={next}
        />
      ),
    },
  },
  {
    form: {
      fields: () => ({
        experience: ["", []],
        jobTitle: ["", []],
      }),
      render: ({ fields, back, next }) => (
        <Form
          key="background"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              experience: z
                .string()
                .nonempty("Please select your years of experience"),
              jobTitle: z
                .string()
                .nonempty("Please enter your current job title"),
            }),
          )}
          heading="Your background"
          message="Tell us about your professional experience."
          content={[
            {
              type: "select",
              name: "experience",
              label: "Years of experience",
              placeholder: "Select years of experience",
              options: constants.yearsOfExperience,
            },
            {
              type: "input",
              name: "jobTitle",
              label: "Current job title",
              placeholder: "Software Engineer",
            },
          ]}
          buttons={{
            back: "Back",
            next: "Continue",
          }}
          back={back}
          next={next}
        />
      ),
    },
  },
  {
    form: {
      fields: () => ({
        employmentType: ["", []],
        workArrangement: ["", []],
      }),
      render: ({ fields, back, next }) => (
        <Form
          key="preferences"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              employmentType: z
                .string()
                .nonempty("Please select an employment type"),
              workArrangement: z
                .string()
                .nonempty("Please select a work arrangement"),
            }),
          )}
          heading="Your preferences"
          message="What kind of role are you looking for?"
          content={[
            {
              type: "select",
              name: "employmentType",
              label: "Employment type",
              placeholder: "Select employment type",
              options: constants.employmentTypes,
            },
            {
              type: "select",
              name: "workArrangement",
              label: "Work arrangement",
              placeholder: "Select work arrangement",
              options: constants.workArrangements,
            },
          ]}
          buttons={{
            back: "Back",
            next: "Continue",
          }}
          back={back}
          next={next}
        />
      ),
    },
  },
  {
    form: {
      fields: () => ({
        whyRole: ["", []],
        greatestStrength: ["", []],
      }),
      render: ({ fields, back, next }) => (
        <Form
          key="about"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              whyRole: z
                .string()
                .nonempty("Please tell us why you want this role"),
              greatestStrength: z
                .string()
                .nonempty("Please share your greatest strength"),
            }),
          )}
          heading="About you"
          message="Help us get to know you a little better."
          content={[
            {
              type: "textarea",
              name: "whyRole",
              label: "Why do you want this role?",
              placeholder: "Tell us what excites you about this opportunity…",
            },
            {
              type: "textarea",
              name: "greatestStrength",
              label: "What is your greatest strength?",
              placeholder: "Describe a strength that sets you apart…",
            },
          ]}
          buttons={{
            back: "Back",
            next: "Continue",
          }}
          back={back}
          next={next}
        />
      ),
    },
  },
  {
    form: {
      fields: () => ({}),
      render: ({ values, params, next }) => (
        <Review
          key="review"
          heading="Review your application"
          message="Everything look right? Submit when you're ready."
          content={[
            {
              text: "Personal details",
              edit: "personal",
              rows: [
                { label: "Full name", value: format.text(values.name) },
                {
                  label: "Email address",
                  value: format.text(values.email),
                },
              ],
            },
            {
              text: "Background",
              edit: "background",
              rows: [
                {
                  label: "Years of experience",
                  value: format.experience(values.experience),
                },
                {
                  label: "Current job title",
                  value: format.text(values.jobTitle),
                },
              ],
            },
            {
              text: "Preferences",
              edit: "preferences",
              rows: [
                {
                  label: "Employment type",
                  value: format.employmentType(values.employmentType),
                },
                {
                  label: "Work arrangement",
                  value: format.workArrangement(values.workArrangement),
                },
              ],
            },
            {
              text: "About you",
              edit: "about",
              rows: [
                {
                  label: "Why this role",
                  value: format.text(values.whyRole),
                },
                {
                  label: "Greatest strength",
                  value: format.text(values.greatestStrength),
                },
              ],
            },
          ]}
          button="Submit application"
          next={next}
          status={params.status}
        />
      ),
    },
  },
  {
    return: (values) => ({
      name: values.name,
      email: values.email,
      experience: values.experience,
      jobTitle: values.jobTitle,
      employmentType: values.employmentType,
      workArrangement: values.workArrangement,
      whyRole: values.whyRole,
      greatestStrength: values.greatestStrength,
    }),
  },
];

The review step is a form element with no fields, which reads all the answers to show from values. The Values type merges the fields of the steps into one object, using UnionToIntersection.

The fourth one is src/app.tsx, which renders the flow using Formity.

TSX
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/react";
import type { Status } from "./types/status";

import { useState, useCallback } from "react";
import { Formity } from "@formity/react";

import { Done } from "./components/done";

import { flow, type Schema } from "./flow";

export default function App() {
  const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
    type: "form",
    submitting: false,
  });

  const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
    setStatus({ type: "form", submitting: true });

    // Show output in the console
    console.log(output);

    // Simulate a network request
    await new Promise((resolve) => setTimeout(resolve, 1000));

    setStatus({ type: "done", output });
  }, []);

  if (status.type === "done") {
    return (
      <Done
        output={status.output}
        onStartOver={() => setStatus({ type: "form", submitting: false })}
      />
    );
  }

  return <Formity flow={flow} params={{ status }} onReturn={onReturn} />;
}

The review step shows the answers, but edit buttons do nothing yet, as onEdit is an empty function. To change an answer, the user has to press back until reaching its form.

Adding jump elements

We'll wrap every step in a jump element, with the form in at and an id that identifies it. This lets the edit buttons jump to any form, and lets each form jump back to the review step.

TSX
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Form } from "./components/form";
import { Review } from "./components/review";

import * as constants from "./constants";
import * as format from "./utils/format";

type Values = UnionToIntersection<Fields[keyof Fields]>;

type Fields = {
  personal: {
    name: string;
    email: string;
  };
  background: {
    experience: string;
    jobTitle: string;
  };
  preferences: {
    employmentType: string;
    workArrangement: string;
  };
  about: {
    whyRole: string;
    greatestStrength: string;
  };
};

export type Schema = {
  render: React.ReactNode;
  struct: [
    s.Jump<s.Form<Fields["personal"]>>,
    s.Jump<s.Form<Fields["background"]>>,
    s.Jump<s.Form<Fields["preferences"]>>,
    s.Jump<s.Form<Fields["about"]>>,
    s.Jump<s.Form<Record<never, never>>>,
    s.Return<Values>,
  ];
  inputs: Record<never, never>;
  params: {
    status: FormStatus;
  };
};

export const flow: Flow<Schema> = [
  {
    jump: {
      id: "personal",
      at: {
        form: {
          fields: () => ({
            name: ["", []],
            email: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="personal"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  name: z.string().nonempty("Please enter your full name"),
                  email: z.email("Please enter a valid email address"),
                }),
              )}
              heading="Personal details"
              message="Let's start with your basic contact information."
              content={[
                {
                  type: "input",
                  name: "name",
                  label: "Full name",
                  placeholder: "Jane Smith",
                },
                {
                  type: "input",
                  name: "email",
                  label: "Email address",
                  placeholder: "jane@example.com",
                },
              ]}
              buttons={{
                back: null,
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "background",
      at: {
        form: {
          fields: () => ({
            experience: ["", []],
            jobTitle: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="background"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  experience: z
                    .string()
                    .nonempty("Please select your years of experience"),
                  jobTitle: z
                    .string()
                    .nonempty("Please enter your current job title"),
                }),
              )}
              heading="Your background"
              message="Tell us about your professional experience."
              content={[
                {
                  type: "select",
                  name: "experience",
                  label: "Years of experience",
                  placeholder: "Select years of experience",
                  options: constants.yearsOfExperience,
                },
                {
                  type: "input",
                  name: "jobTitle",
                  label: "Current job title",
                  placeholder: "Software Engineer",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "preferences",
      at: {
        form: {
          fields: () => ({
            employmentType: ["", []],
            workArrangement: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="preferences"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  employmentType: z
                    .string()
                    .nonempty("Please select an employment type"),
                  workArrangement: z
                    .string()
                    .nonempty("Please select a work arrangement"),
                }),
              )}
              heading="Your preferences"
              message="What kind of role are you looking for?"
              content={[
                {
                  type: "select",
                  name: "employmentType",
                  label: "Employment type",
                  placeholder: "Select employment type",
                  options: constants.employmentTypes,
                },
                {
                  type: "select",
                  name: "workArrangement",
                  label: "Work arrangement",
                  placeholder: "Select work arrangement",
                  options: constants.workArrangements,
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "about",
      at: {
        form: {
          fields: () => ({
            whyRole: ["", []],
            greatestStrength: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="about"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  whyRole: z
                    .string()
                    .nonempty("Please tell us why you want this role"),
                  greatestStrength: z
                    .string()
                    .nonempty("Please share your greatest strength"),
                }),
              )}
              heading="About you"
              message="Help us get to know you a little better."
              content={[
                {
                  type: "textarea",
                  name: "whyRole",
                  label: "Why do you want this role?",
                  placeholder:
                    "Tell us what excites you about this opportunity…",
                },
                {
                  type: "textarea",
                  name: "greatestStrength",
                  label: "What is your greatest strength?",
                  placeholder: "Describe a strength that sets you apart…",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "review",
      at: {
        form: {
          fields: () => ({}),
          render: ({ values, params, next }) => (
            <Review
              key="review"
              heading="Review your application"
              message="Everything look right? Submit when you're ready."
              content={[
                {
                  text: "Personal details",
                  edit: "personal",
                  rows: [
                    { label: "Full name", value: format.text(values.name) },
                    {
                      label: "Email address",
                      value: format.text(values.email),
                    },
                  ],
                },
                {
                  text: "Background",
                  edit: "background",
                  rows: [
                    {
                      label: "Years of experience",
                      value: format.experience(values.experience),
                    },
                    {
                      label: "Current job title",
                      value: format.text(values.jobTitle),
                    },
                  ],
                },
                {
                  text: "Preferences",
                  edit: "preferences",
                  rows: [
                    {
                      label: "Employment type",
                      value: format.employmentType(values.employmentType),
                    },
                    {
                      label: "Work arrangement",
                      value: format.workArrangement(values.workArrangement),
                    },
                  ],
                },
                {
                  text: "About you",
                  edit: "about",
                  rows: [
                    {
                      label: "Why this role",
                      value: format.text(values.whyRole),
                    },
                    {
                      label: "Greatest strength",
                      value: format.text(values.greatestStrength),
                    },
                  ],
                },
              ]}
              button="Submit application"
              next={next}
              status={params.status}
            />
          ),
        },
      },
    },
  },
  {
    return: (values) => ({
      name: values.name,
      email: values.email,
      experience: values.experience,
      jobTitle: values.jobTitle,
      employmentType: values.employmentType,
      workArrangement: values.workArrangement,
      whyRole: values.whyRole,
      greatestStrength: values.greatestStrength,
    }),
  },
];

Fixing type errors

There are type errors now where the flow values are read, like values.name in the review step. A jump element can be reached from anywhere, so Formity can't assume the previous steps were completed.

To fix them we provide default values with inputs, which always exist. We type them as Values in the Schema and export an inputs object with a default value for each field.

TSX
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Form } from "./components/form";
import { Review } from "./components/review";

import * as constants from "./constants";
import * as format from "./utils/format";

type Values = UnionToIntersection<Fields[keyof Fields]>;

type Fields = {
  personal: {
    name: string;
    email: string;
  };
  background: {
    experience: string;
    jobTitle: string;
  };
  preferences: {
    employmentType: string;
    workArrangement: string;
  };
  about: {
    whyRole: string;
    greatestStrength: string;
  };
};

export type Schema = {
  render: React.ReactNode;
  struct: [
    s.Jump<s.Form<Fields["personal"]>>,
    s.Jump<s.Form<Fields["background"]>>,
    s.Jump<s.Form<Fields["preferences"]>>,
    s.Jump<s.Form<Fields["about"]>>,
    s.Jump<s.Form<Record<never, never>>>,
    s.Return<Values>,
  ];
  inputs: Values;
  params: {
    status: FormStatus;
  };
};

export const flow: Flow<Schema> = [
  {
    jump: {
      id: "personal",
      at: {
        form: {
          fields: () => ({
            name: ["", []],
            email: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="personal"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  name: z.string().nonempty("Please enter your full name"),
                  email: z.email("Please enter a valid email address"),
                }),
              )}
              heading="Personal details"
              message="Let's start with your basic contact information."
              content={[
                {
                  type: "input",
                  name: "name",
                  label: "Full name",
                  placeholder: "Jane Smith",
                },
                {
                  type: "input",
                  name: "email",
                  label: "Email address",
                  placeholder: "jane@example.com",
                },
              ]}
              buttons={{
                back: null,
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "background",
      at: {
        form: {
          fields: () => ({
            experience: ["", []],
            jobTitle: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="background"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  experience: z
                    .string()
                    .nonempty("Please select your years of experience"),
                  jobTitle: z
                    .string()
                    .nonempty("Please enter your current job title"),
                }),
              )}
              heading="Your background"
              message="Tell us about your professional experience."
              content={[
                {
                  type: "select",
                  name: "experience",
                  label: "Years of experience",
                  placeholder: "Select years of experience",
                  options: constants.yearsOfExperience,
                },
                {
                  type: "input",
                  name: "jobTitle",
                  label: "Current job title",
                  placeholder: "Software Engineer",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "preferences",
      at: {
        form: {
          fields: () => ({
            employmentType: ["", []],
            workArrangement: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="preferences"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  employmentType: z
                    .string()
                    .nonempty("Please select an employment type"),
                  workArrangement: z
                    .string()
                    .nonempty("Please select a work arrangement"),
                }),
              )}
              heading="Your preferences"
              message="What kind of role are you looking for?"
              content={[
                {
                  type: "select",
                  name: "employmentType",
                  label: "Employment type",
                  placeholder: "Select employment type",
                  options: constants.employmentTypes,
                },
                {
                  type: "select",
                  name: "workArrangement",
                  label: "Work arrangement",
                  placeholder: "Select work arrangement",
                  options: constants.workArrangements,
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "about",
      at: {
        form: {
          fields: () => ({
            whyRole: ["", []],
            greatestStrength: ["", []],
          }),
          render: ({ fields, back, next }) => (
            <Form
              key="about"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  whyRole: z
                    .string()
                    .nonempty("Please tell us why you want this role"),
                  greatestStrength: z
                    .string()
                    .nonempty("Please share your greatest strength"),
                }),
              )}
              heading="About you"
              message="Help us get to know you a little better."
              content={[
                {
                  type: "textarea",
                  name: "whyRole",
                  label: "Why do you want this role?",
                  placeholder:
                    "Tell us what excites you about this opportunity…",
                },
                {
                  type: "textarea",
                  name: "greatestStrength",
                  label: "What is your greatest strength?",
                  placeholder: "Describe a strength that sets you apart…",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              back={back}
              next={next}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "review",
      at: {
        form: {
          fields: () => ({}),
          render: ({ values, params, next }) => (
            <Review
              key="review"
              heading="Review your application"
              message="Everything look right? Submit when you're ready."
              content={[
                {
                  text: "Personal details",
                  edit: "personal",
                  rows: [
                    { label: "Full name", value: format.text(values.name) },
                    {
                      label: "Email address",
                      value: format.text(values.email),
                    },
                  ],
                },
                {
                  text: "Background",
                  edit: "background",
                  rows: [
                    {
                      label: "Years of experience",
                      value: format.experience(values.experience),
                    },
                    {
                      label: "Current job title",
                      value: format.text(values.jobTitle),
                    },
                  ],
                },
                {
                  text: "Preferences",
                  edit: "preferences",
                  rows: [
                    {
                      label: "Employment type",
                      value: format.employmentType(values.employmentType),
                    },
                    {
                      label: "Work arrangement",
                      value: format.workArrangement(values.workArrangement),
                    },
                  ],
                },
                {
                  text: "About you",
                  edit: "about",
                  rows: [
                    {
                      label: "Why this role",
                      value: format.text(values.whyRole),
                    },
                    {
                      label: "Greatest strength",
                      value: format.text(values.greatestStrength),
                    },
                  ],
                },
              ]}
              button="Submit application"
              next={next}
              status={params.status}
            />
          ),
        },
      },
    },
  },
  {
    return: (values) => ({
      name: values.name,
      email: values.email,
      experience: values.experience,
      jobTitle: values.jobTitle,
      employmentType: values.employmentType,
      workArrangement: values.workArrangement,
      whyRole: values.whyRole,
      greatestStrength: values.greatestStrength,
    }),
  },
];

export const inputs: Values = {
  name: "",
  email: "",
  experience: "",
  jobTitle: "",
  employmentType: "",
  workArrangement: "",
  whyRole: "",
  greatestStrength: "",
};

Finally, we pass this object to Formity through its inputs prop, as shown below. With that the type errors are gone, since every value now exists from the start.

TSX
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/react";
import type { Status } from "./types/status";

import { useState, useCallback } from "react";
import { Formity } from "@formity/react";

import { Done } from "./components/done";

import { flow, inputs, type Schema } from "./flow";

export default function App() {
  const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
    type: "form",
    submitting: false,
  });

  const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
    setStatus({ type: "form", submitting: true });

    // Show output in the console
    console.log(output);

    // Simulate a network request
    await new Promise((resolve) => setTimeout(resolve, 1000));

    setStatus({ type: "done", output });
  }, []);

  if (status.type === "done") {
    return (
      <Done
        output={status.output}
        onStartOver={() => setStatus({ type: "form", submitting: false })}
      />
    );
  }

  return (
    <Formity
      flow={flow}
      inputs={inputs}
      params={{ status }}
      onReturn={onReturn}
    />
  );
}

The back function goes to the previously visited step. If the user jumped from the review step to a form, pressing back would return to the review step instead of the previous form.

We need to update the Form component so the back button uses jump instead. The back prop is replaced by jump, and a new prev prop holds the id of the previous form.

TSX
// src/components/form/index.tsx
import type { DefaultValues, Resolver } from "react-hook-form";
import type { Next, Jump } from "@formity/react";

import { useForm, FormProvider } from "react-hook-form";

import { ItemView, type Item } from "./item";
import { Button } from "../button";

interface FormProps<T extends Record<string, unknown>> {
  defaultValues: DefaultValues<T>;
  resolver: Resolver<T>;
  heading: string;
  message: string;
  content: Item[];
  buttons: {
    back: string | null;
    next: string;
  };
  next: Next<T>;
  jump: Jump<T>;
  prev: string | null;
}

export function Form<T extends Record<string, unknown>>({
  defaultValues,
  resolver,
  heading,
  message,
  content,
  buttons,
  next,
  jump,
  prev,
}: FormProps<T>) {
  const form = useForm({ defaultValues, resolver });
  return (
    <div className="flex h-full w-full items-center justify-center overflow-y-auto bg-white px-4 py-12">
      <div className="w-full max-w-lg">
        <form noValidate autoComplete="off" onSubmit={form.handleSubmit(next)}>
          <FormProvider {...form}>
            <div className="mb-8">
              <h2 className="mb-1.5 text-2xl font-bold text-gray-950">
                {heading}
              </h2>
              <p className="text-sm font-medium text-gray-400">{message}</p>
            </div>
            <div className="mb-8 flex flex-col gap-6">
              {content.map((item, i) => (
                <ItemView key={i} {...item} />
              ))}
            </div>
            <div className="flex w-full items-center justify-end gap-4">
              {buttons.back && (
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => jump(prev, form.getValues())}
                >
                  {buttons.back}
                </Button>
              )}
              <Button type="submit" variant="primary">
                {buttons.next}
              </Button>
            </div>
          </FormProvider>
        </form>
      </div>
    </div>
  );
}

Then, we also update the Review component. It now receives jump, which each edit button calls to go to the corresponding form, passing an empty object since the review step has no fields.

TSX
// src/components/review/index.tsx
import type { Next, Jump } from "@formity/react";
import type { FormStatus } from "../../types/status";

import { ItemView, type Item } from "./item";
import { Button } from "../button";

interface ReviewProps {
  heading: string;
  message: string;
  content: Item[];
  button: string;
  next: Next<Record<never, never>>;
  jump: Jump<Record<never, never>>;
  status: FormStatus;
}

export function Review({
  heading,
  message,
  content,
  button,
  next,
  jump,
  status,
}: ReviewProps) {
  return (
    <div className="flex h-full w-full items-center justify-center overflow-y-auto bg-white px-4 py-12">
      <div className="w-full max-w-lg">
        <div className="mb-8">
          <h2 className="mb-1.5 text-2xl font-bold text-gray-950">{heading}</h2>
          <p className="text-sm font-medium text-gray-400">{message}</p>
        </div>
        <div className="mb-8 flex flex-col gap-4">
          {content.map((item, i) => (
            <ItemView key={i} item={item} onEdit={(edit) => jump(edit, {})} />
          ))}
        </div>
        <div className="flex w-full items-center justify-end gap-4">
          <Button
            variant="primary"
            onClick={() => next({})}
            disabled={status.submitting}
          >
            {status.submitting ? "Submitting..." : button}
          </Button>
        </div>
      </div>
    </div>
  );
}

The components are ready, but the flow still passes them the old props. Once we update it, both the edit buttons and the back button navigate with jumps.

TSX
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Form } from "./components/form";
import { Review } from "./components/review";

import * as constants from "./constants";
import * as format from "./utils/format";

type Values = UnionToIntersection<Fields[keyof Fields]>;

type Fields = {
  personal: {
    name: string;
    email: string;
  };
  background: {
    experience: string;
    jobTitle: string;
  };
  preferences: {
    employmentType: string;
    workArrangement: string;
  };
  about: {
    whyRole: string;
    greatestStrength: string;
  };
};

export type Schema = {
  render: React.ReactNode;
  struct: [
    s.Jump<s.Form<Fields["personal"]>>,
    s.Jump<s.Form<Fields["background"]>>,
    s.Jump<s.Form<Fields["preferences"]>>,
    s.Jump<s.Form<Fields["about"]>>,
    s.Jump<s.Form<Record<never, never>>>,
    s.Return<Values>,
  ];
  inputs: Values;
  params: {
    status: FormStatus;
  };
};

export const flow: Flow<Schema> = [
  {
    jump: {
      id: "personal",
      at: {
        form: {
          fields: () => ({
            name: ["", []],
            email: ["", []],
          }),
          render: ({ fields, next, jump }) => (
            <Form
              key="personal"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  name: z.string().nonempty("Please enter your full name"),
                  email: z.email("Please enter a valid email address"),
                }),
              )}
              heading="Personal details"
              message="Let's start with your basic contact information."
              content={[
                {
                  type: "input",
                  name: "name",
                  label: "Full name",
                  placeholder: "Jane Smith",
                },
                {
                  type: "input",
                  name: "email",
                  label: "Email address",
                  placeholder: "jane@example.com",
                },
              ]}
              buttons={{
                back: null,
                next: "Continue",
              }}
              next={next}
              jump={jump}
              prev={null}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "background",
      at: {
        form: {
          fields: () => ({
            experience: ["", []],
            jobTitle: ["", []],
          }),
          render: ({ fields, next, jump }) => (
            <Form
              key="background"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  experience: z
                    .string()
                    .nonempty("Please select your years of experience"),
                  jobTitle: z
                    .string()
                    .nonempty("Please enter your current job title"),
                }),
              )}
              heading="Your background"
              message="Tell us about your professional experience."
              content={[
                {
                  type: "select",
                  name: "experience",
                  label: "Years of experience",
                  placeholder: "Select years of experience",
                  options: constants.yearsOfExperience,
                },
                {
                  type: "input",
                  name: "jobTitle",
                  label: "Current job title",
                  placeholder: "Software Engineer",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              next={next}
              jump={jump}
              prev="personal"
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "preferences",
      at: {
        form: {
          fields: () => ({
            employmentType: ["", []],
            workArrangement: ["", []],
          }),
          render: ({ fields, next, jump }) => (
            <Form
              key="preferences"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  employmentType: z
                    .string()
                    .nonempty("Please select an employment type"),
                  workArrangement: z
                    .string()
                    .nonempty("Please select a work arrangement"),
                }),
              )}
              heading="Your preferences"
              message="What kind of role are you looking for?"
              content={[
                {
                  type: "select",
                  name: "employmentType",
                  label: "Employment type",
                  placeholder: "Select employment type",
                  options: constants.employmentTypes,
                },
                {
                  type: "select",
                  name: "workArrangement",
                  label: "Work arrangement",
                  placeholder: "Select work arrangement",
                  options: constants.workArrangements,
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              next={next}
              jump={jump}
              prev="background"
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "about",
      at: {
        form: {
          fields: () => ({
            whyRole: ["", []],
            greatestStrength: ["", []],
          }),
          render: ({ fields, next, jump }) => (
            <Form
              key="about"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  whyRole: z
                    .string()
                    .nonempty("Please tell us why you want this role"),
                  greatestStrength: z
                    .string()
                    .nonempty("Please share your greatest strength"),
                }),
              )}
              heading="About you"
              message="Help us get to know you a little better."
              content={[
                {
                  type: "textarea",
                  name: "whyRole",
                  label: "Why do you want this role?",
                  placeholder:
                    "Tell us what excites you about this opportunity…",
                },
                {
                  type: "textarea",
                  name: "greatestStrength",
                  label: "What is your greatest strength?",
                  placeholder: "Describe a strength that sets you apart…",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
              }}
              next={next}
              jump={jump}
              prev="preferences"
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "review",
      at: {
        form: {
          fields: () => ({}),
          render: ({ values, params, next, jump }) => (
            <Review
              key="review"
              heading="Review your application"
              message="Everything look right? Submit when you're ready."
              content={[
                {
                  text: "Personal details",
                  edit: "personal",
                  rows: [
                    { label: "Full name", value: format.text(values.name) },
                    {
                      label: "Email address",
                      value: format.text(values.email),
                    },
                  ],
                },
                {
                  text: "Background",
                  edit: "background",
                  rows: [
                    {
                      label: "Years of experience",
                      value: format.experience(values.experience),
                    },
                    {
                      label: "Current job title",
                      value: format.text(values.jobTitle),
                    },
                  ],
                },
                {
                  text: "Preferences",
                  edit: "preferences",
                  rows: [
                    {
                      label: "Employment type",
                      value: format.employmentType(values.employmentType),
                    },
                    {
                      label: "Work arrangement",
                      value: format.workArrangement(values.workArrangement),
                    },
                  ],
                },
                {
                  text: "About you",
                  edit: "about",
                  rows: [
                    {
                      label: "Why this role",
                      value: format.text(values.whyRole),
                    },
                    {
                      label: "Greatest strength",
                      value: format.text(values.greatestStrength),
                    },
                  ],
                },
              ]}
              button="Submit application"
              next={next}
              jump={jump}
              status={params.status}
            />
          ),
        },
      },
    },
  },
  {
    return: (values) => ({
      name: values.name,
      email: values.email,
      experience: values.experience,
      jobTitle: values.jobTitle,
      employmentType: values.employmentType,
      workArrangement: values.workArrangement,
      whyRole: values.whyRole,
      greatestStrength: values.greatestStrength,
    }),
  },
];

export const inputs: Values = {
  name: "",
  email: "",
  experience: "",
  jobTitle: "",
  employmentType: "",
  workArrangement: "",
  whyRole: "",
  greatestStrength: "",
};

Disabling history

We don't use back anymore, so there's no reason for Formity to keep track of the visited steps. Setting the history prop to false disables it.

TSX
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/react";
import type { Status } from "./types/status";

import { useState, useCallback } from "react";
import { Formity } from "@formity/react";

import { Done } from "./components/done";

import { flow, inputs, type Schema } from "./flow";

export default function App() {
  const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
    type: "form",
    submitting: false,
  });

  const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
    setStatus({ type: "form", submitting: true });

    // Show output in the console
    console.log(output);

    // Simulate a network request
    await new Promise((resolve) => setTimeout(resolve, 1000));

    setStatus({ type: "done", output });
  }, []);

  if (status.type === "done") {
    return (
      <Done
        output={status.output}
        onStartOver={() => setStatus({ type: "form", submitting: false })}
      />
    );
  }

  return (
    <Formity
      flow={flow}
      inputs={inputs}
      params={{ status }}
      history={false}
      onReturn={onReturn}
    />
  );
}

Jumping to review

When the user clicks an edit button and lands on a previous form, the submit button should jump straight back to the review step instead of continuing forward through the flow.

To support this, we add an edit prop to the Form component that tells whether the user is editing. If so, a valid submission jumps to the review step instead of calling next.

The buttons change as well while editing. The back button is hidden, and the submit button shows the label from a new edit property of buttons.

TSX
// src/components/form/index.tsx
import type { DefaultValues, Resolver } from "react-hook-form";
import type { Next, Jump } from "@formity/react";

import { useForm, FormProvider } from "react-hook-form";

import { ItemView, type Item } from "./item";
import { Button } from "../button";

interface FormProps<T extends Record<string, unknown>> {
  defaultValues: DefaultValues<T>;
  resolver: Resolver<T>;
  heading: string;
  message: string;
  content: Item[];
  buttons: {
    back: string | null;
    next: string;
    edit: string;
  };
  next: Next<T>;
  jump: Jump<T>;
  prev: string | null;
  edit: boolean;
}

export function Form<T extends Record<string, unknown>>({
  defaultValues,
  resolver,
  heading,
  message,
  content,
  buttons,
  next,
  jump,
  prev,
  edit,
}: FormProps<T>) {
  const form = useForm({ defaultValues, resolver });
  return (
    <div className="flex h-full w-full items-center justify-center overflow-y-auto bg-white px-4 py-12">
      <div className="w-full max-w-lg">
        <form
          noValidate
          autoComplete="off"
          onSubmit={form.handleSubmit((fields) => {
            if (edit) jump("review", fields);
            else next(fields);
          })}
        >
          <FormProvider {...form}>
            <div className="mb-8">
              <h2 className="mb-1.5 text-2xl font-bold text-gray-950">
                {heading}
              </h2>
              <p className="text-sm font-medium text-gray-400">{message}</p>
            </div>
            <div className="mb-8 flex flex-col gap-6">
              {content.map((item, i) => (
                <ItemView key={i} {...item} />
              ))}
            </div>
            <div className="flex w-full items-center justify-end gap-4">
              {buttons.back && !edit && (
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => jump(prev, form.getValues())}
                >
                  {buttons.back}
                </Button>
              )}
              <Button type="submit" variant="primary">
                {edit ? buttons.edit : buttons.next}
              </Button>
            </div>
          </FormProvider>
        </form>
      </div>
    </div>
  );
}

The flow gets an edit value that starts as false in inputs. A variables element before the review step sets it to true, and it stays that way since jumps keep the flow values.

We pass this value to Form through its edit prop, reading it from the values that each render function receives. We also add the edit label to buttons.

TSX
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";

import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Form } from "./components/form";
import { Review } from "./components/review";

import * as constants from "./constants";
import * as format from "./utils/format";

type Values = UnionToIntersection<Fields[keyof Fields]>;

type Fields = {
  personal: {
    name: string;
    email: string;
  };
  background: {
    experience: string;
    jobTitle: string;
  };
  preferences: {
    employmentType: string;
    workArrangement: string;
  };
  about: {
    whyRole: string;
    greatestStrength: string;
  };
};

export type Schema = {
  render: React.ReactNode;
  struct: [
    s.Jump<s.Form<Fields["personal"]>>,
    s.Jump<s.Form<Fields["background"]>>,
    s.Jump<s.Form<Fields["preferences"]>>,
    s.Jump<s.Form<Fields["about"]>>,
    s.Variables<{ edit: boolean }>,
    s.Jump<s.Form<Record<never, never>>>,
    s.Return<Values>,
  ];
  inputs: Values & { edit: boolean };
  params: {
    status: FormStatus;
  };
};

export const flow: Flow<Schema> = [
  {
    jump: {
      id: "personal",
      at: {
        form: {
          fields: () => ({
            name: ["", []],
            email: ["", []],
          }),
          render: ({ fields, values, next, jump }) => (
            <Form
              key="personal"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  name: z.string().nonempty("Please enter your full name"),
                  email: z.email("Please enter a valid email address"),
                }),
              )}
              heading="Personal details"
              message="Let's start with your basic contact information."
              content={[
                {
                  type: "input",
                  name: "name",
                  label: "Full name",
                  placeholder: "Jane Smith",
                },
                {
                  type: "input",
                  name: "email",
                  label: "Email address",
                  placeholder: "jane@example.com",
                },
              ]}
              buttons={{
                back: null,
                next: "Continue",
                edit: "Save & review",
              }}
              next={next}
              jump={jump}
              prev={null}
              edit={values.edit}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "background",
      at: {
        form: {
          fields: () => ({
            experience: ["", []],
            jobTitle: ["", []],
          }),
          render: ({ fields, values, next, jump }) => (
            <Form
              key="background"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  experience: z
                    .string()
                    .nonempty("Please select your years of experience"),
                  jobTitle: z
                    .string()
                    .nonempty("Please enter your current job title"),
                }),
              )}
              heading="Your background"
              message="Tell us about your professional experience."
              content={[
                {
                  type: "select",
                  name: "experience",
                  label: "Years of experience",
                  placeholder: "Select years of experience",
                  options: constants.yearsOfExperience,
                },
                {
                  type: "input",
                  name: "jobTitle",
                  label: "Current job title",
                  placeholder: "Software Engineer",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
                edit: "Save & review",
              }}
              next={next}
              jump={jump}
              prev="personal"
              edit={values.edit}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "preferences",
      at: {
        form: {
          fields: () => ({
            employmentType: ["", []],
            workArrangement: ["", []],
          }),
          render: ({ fields, values, next, jump }) => (
            <Form
              key="preferences"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  employmentType: z
                    .string()
                    .nonempty("Please select an employment type"),
                  workArrangement: z
                    .string()
                    .nonempty("Please select a work arrangement"),
                }),
              )}
              heading="Your preferences"
              message="What kind of role are you looking for?"
              content={[
                {
                  type: "select",
                  name: "employmentType",
                  label: "Employment type",
                  placeholder: "Select employment type",
                  options: constants.employmentTypes,
                },
                {
                  type: "select",
                  name: "workArrangement",
                  label: "Work arrangement",
                  placeholder: "Select work arrangement",
                  options: constants.workArrangements,
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
                edit: "Save & review",
              }}
              next={next}
              jump={jump}
              prev="background"
              edit={values.edit}
            />
          ),
        },
      },
    },
  },
  {
    jump: {
      id: "about",
      at: {
        form: {
          fields: () => ({
            whyRole: ["", []],
            greatestStrength: ["", []],
          }),
          render: ({ fields, values, next, jump }) => (
            <Form
              key="about"
              defaultValues={fields}
              resolver={zodResolver(
                z.object({
                  whyRole: z
                    .string()
                    .nonempty("Please tell us why you want this role"),
                  greatestStrength: z
                    .string()
                    .nonempty("Please share your greatest strength"),
                }),
              )}
              heading="About you"
              message="Help us get to know you a little better."
              content={[
                {
                  type: "textarea",
                  name: "whyRole",
                  label: "Why do you want this role?",
                  placeholder:
                    "Tell us what excites you about this opportunity…",
                },
                {
                  type: "textarea",
                  name: "greatestStrength",
                  label: "What is your greatest strength?",
                  placeholder: "Describe a strength that sets you apart…",
                },
              ]}
              buttons={{
                back: "Back",
                next: "Continue",
                edit: "Save & review",
              }}
              next={next}
              jump={jump}
              prev="preferences"
              edit={values.edit}
            />
          ),
        },
      },
    },
  },
  {
    variables: () => ({
      edit: true,
    }),
  },
  {
    jump: {
      id: "review",
      at: {
        form: {
          fields: () => ({}),
          render: ({ values, params, next, jump }) => (
            <Review
              key="review"
              heading="Review your application"
              message="Everything look right? Submit when you're ready."
              content={[
                {
                  text: "Personal details",
                  edit: "personal",
                  rows: [
                    { label: "Full name", value: format.text(values.name) },
                    {
                      label: "Email address",
                      value: format.text(values.email),
                    },
                  ],
                },
                {
                  text: "Background",
                  edit: "background",
                  rows: [
                    {
                      label: "Years of experience",
                      value: format.experience(values.experience),
                    },
                    {
                      label: "Current job title",
                      value: format.text(values.jobTitle),
                    },
                  ],
                },
                {
                  text: "Preferences",
                  edit: "preferences",
                  rows: [
                    {
                      label: "Employment type",
                      value: format.employmentType(values.employmentType),
                    },
                    {
                      label: "Work arrangement",
                      value: format.workArrangement(values.workArrangement),
                    },
                  ],
                },
                {
                  text: "About you",
                  edit: "about",
                  rows: [
                    {
                      label: "Why this role",
                      value: format.text(values.whyRole),
                    },
                    {
                      label: "Greatest strength",
                      value: format.text(values.greatestStrength),
                    },
                  ],
                },
              ]}
              button="Submit application"
              next={next}
              jump={jump}
              status={params.status}
            />
          ),
        },
      },
    },
  },
  {
    return: (values) => ({
      name: values.name,
      email: values.email,
      experience: values.experience,
      jobTitle: values.jobTitle,
      employmentType: values.employmentType,
      workArrangement: values.workArrangement,
      whyRole: values.whyRole,
      greatestStrength: values.greatestStrength,
    }),
  },
];

export const inputs: Schema["inputs"] = {
  name: "",
  email: "",
  experience: "",
  jobTitle: "",
  employmentType: "",
  workArrangement: "",
  whyRole: "",
  greatestStrength: "",
  edit: false,
};