GuidesConditional fields

Guides

Conditional fields

Learn how to add fields that appear when a condition is met.


Initial steps

We'll show you how to add fields that appear when a condition is met. To follow along, start by cloning the repository below, which contains the code we'll use as the starting point.

Terminal
git clone https://github.com/martiserra99/formity-react-hook-form

Then install the dependencies.

Terminal
npm install

The repo is a React project using Vite and TypeScript, with @formity/react already installed for you. Its code is the multi-step form from the React Hook Form page, and we'll build on top of it.

Before we start

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

The first one is src/components/form/item/index.tsx, with Item and ItemView.

TSX
// src/components/form/item/index.tsx
import { ColumnsView, type Columns } from "./columns";
import { InputView, type Input } from "./input";
import { NumberView, type Number } from "./number";
import { SelectView, type Select } from "./select";
import { TextareaView, type Textarea } from "./textarea";
import { MultiSelectView, type MultiSelect } from "./multi-select";

export type Item = Columns | Input | Number | Select | Textarea | MultiSelect;

export function ItemView(item: Item) {
  switch (item.type) {
    case "columns": {
      return <ColumnsView {...item} />;
    }
    case "input": {
      return <InputView {...item} />;
    }
    case "number": {
      return <NumberView {...item} />;
    }
    case "select": {
      return <SelectView {...item} />;
    }
    case "textarea": {
      return <TextareaView {...item} />;
    }
    case "multi-select": {
      return <MultiSelectView {...item} />;
    }
  }
}

The Item type is the union of all the items that a step can show, such as an input or a select field. Each item is rendered by ItemView, which picks the right component from its type property.

The second one is src/components/form/item/columns.tsx, with the columns item.

TSX
// src/components/form/item/columns.tsx
import { ItemView, type Item } from ".";

export interface Columns {
  type: "columns";
  columns: Item[];
}

export function ColumnsView({ columns }: Columns) {
  return (
    <div className="grid grid-cols-2 gap-3.5">
      {columns.map((item, i) => (
        <ItemView key={i} {...item} />
      ))}
    </div>
  );
}

The columns item is used to render two items next to each other. It's the only item that contains other items, so it's the only one that uses ItemView.

The third 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 type { FormStatus } from "@/types/status";

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;
  content: Item[];
  buttons: {
    back: string | null;
    next: string;
  };
  back: Back<T>;
  next: Next<T>;
  status: FormStatus;
}

export function Form<T extends Record<string, unknown>>({
  defaultValues,
  resolver,
  heading,
  content,
  buttons,
  back,
  next,
  status,
}: FormProps<T>) {
  const form = useForm({ defaultValues, resolver });
  return (
    <form
      onSubmit={form.handleSubmit(next)}
      className="flex h-screen w-full items-center justify-center px-4 py-8"
      autoComplete="off"
    >
      <FormProvider {...form}>
        <div className="w-full max-w-md">
          <h2 className="mb-6 text-center text-4xl font-bold text-gray-950">
            {heading}
          </h2>
          <div className="mb-6 flex flex-col gap-4">
            {content.map((field, index) => (
              <ItemView key={index} {...field} />
            ))}
          </div>
          <div className="flex gap-4">
            {buttons.back && (
              <Button
                type="button"
                variant="secondary"
                disabled={status.submitting}
                onClick={() => back(form.getValues())}
              >
                {buttons.back}
              </Button>
            )}
            <Button
              type="submit"
              variant="primary"
              disabled={status.submitting}
            >
              {status.submitting ? "Submitting..." : buttons.next}
            </Button>
          </div>
        </div>
      </FormProvider>
    </form>
  );
}

The content prop is the array of items to show in the step, each one rendered with ItemView. They're inside FormProvider, so they can access the form with useFormContext.

The fourth one is src/app.tsx, which contains the Schema, the flow and the App component.

TSX
// src/app.tsx
import { useCallback, useState } from "react";

import {
  Formity,
  type s,
  type Flow,
  type OnReturn,
  type ReturnOutput,
} from "@formity/react";

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

import type { Status, FormStatus } from "./types/status";

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

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<{ name: string; surname: string; age: number }>,
    s.Form<{ softwareDeveloper: string }>,
    s.Condition<{
      then: [
        s.Form<{ expertise: string }>,
        s.Return<{
          name: string;
          surname: string;
          age: number;
          softwareDeveloper: true;
          expertise: string;
        }>,
      ];
      else: [
        s.Form<{ interested: string }>,
        s.Return<{
          name: string;
          surname: string;
          age: number;
          softwareDeveloper: false;
          interested: string;
        }>,
      ];
    }>,
  ];
  inputs: Record<never, never>;
  params: {
    status: FormStatus;
  };
};

const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({
        name: ["", []],
        surname: ["", []],
        age: [20, []],
      }),
      render: ({ fields, params, back, next }) => (
        <Form
          key="yourself"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              name: z.string().nonempty("Required"),
              surname: z.string().nonempty("Required"),
              age: z.number().min(18, "Min. 18").max(99, "Max. 99"),
            }),
          )}
          heading="Tell us about yourself"
          content={[
            {
              type: "columns",
              columns: [
                {
                  type: "input",
                  name: "name",
                  label: "Name",
                  placeholder: "Your name",
                },
                {
                  type: "input",
                  name: "surname",
                  label: "Surname",
                  placeholder: "Your surname",
                },
              ],
            },
            {
              type: "number",
              name: "age",
              label: "Age",
              placeholder: "Your age",
            },
          ]}
          buttons={{
            back: null,
            next: "Next",
          }}
          back={back}
          next={next}
          status={params.status}
        />
      ),
    },
  },
  {
    form: {
      fields: () => ({
        softwareDeveloper: ["", []],
      }),
      render: ({ fields, params, back, next }) => (
        <Form
          key="softwareDeveloper"
          defaultValues={fields}
          resolver={zodResolver(
            z.object({
              softwareDeveloper: z.string().nonempty("Required"),
            }),
          )}
          heading="Are you a software developer?"
          content={[
            {
              type: "select",
              name: "softwareDeveloper",
              label: "Software Developer",
              placeholder: "Select an option",
              options: [
                { value: "yes", label: "Yes" },
                { value: "no", label: "No" },
              ],
            },
          ]}
          buttons={{
            back: "Back",
            next: "Next",
          }}
          back={back}
          next={next}
          status={params.status}
        />
      ),
    },
  },
  {
    condition: {
      if: ({ softwareDeveloper }) => softwareDeveloper === "yes",
      then: [
        {
          form: {
            fields: () => ({
              expertise: ["", []],
            }),
            render: ({ fields, params, back, next }) => (
              <Form
                key="expertise"
                defaultValues={fields}
                resolver={zodResolver(
                  z.object({
                    expertise: z.string().nonempty("Required"),
                  }),
                )}
                heading="What is your area of expertise?"
                content={[
                  {
                    type: "select",
                    name: "expertise",
                    label: "Expertise",
                    placeholder: "Select an option",
                    options: [
                      { value: "frontend", label: "Frontend development" },
                      { value: "backend", label: "Backend development" },
                      { value: "mobile", label: "Mobile development" },
                    ],
                  },
                ]}
                buttons={{
                  back: "Back",
                  next: "Submit",
                }}
                back={back}
                next={next}
                status={params.status}
              />
            ),
          },
        },
        {
          return: ({ name, surname, age, expertise }) => ({
            name,
            surname,
            age,
            softwareDeveloper: true,
            expertise,
          }),
        },
      ],
      else: [
        {
          form: {
            fields: () => ({
              interested: ["", []],
            }),
            render: ({ fields, params, back, next }) => (
              <Form
                key="interested"
                defaultValues={fields}
                resolver={zodResolver(
                  z.object({
                    interested: z.string().nonempty("Required"),
                  }),
                )}
                heading="Are you interested in learning how to code?"
                content={[
                  {
                    type: "select",
                    name: "interested",
                    label: "Interested",
                    placeholder: "Select an option",
                    options: [
                      { value: "yes", label: "Yes, I am interested." },
                      { value: "no", label: "No, it is not for me." },
                      { value: "maybe", label: "Maybe, I am not sure." },
                    ],
                  },
                ]}
                buttons={{
                  back: "Back",
                  next: "Submit",
                }}
                back={back}
                next={next}
                status={params.status}
              />
            ),
          },
        },
        {
          return: ({ name, surname, age, interested }) => ({
            name,
            surname,
            age,
            softwareDeveloper: false,
            interested,
          }),
        },
      ],
    },
  },
];

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<Schema> flow={flow} params={{ status }} onReturn={onReturn} />
  );
}

With this code, every item that we put in content is always rendered. There's no way yet to show or hide some of them depending on the values that the user enters in the form.

Create components

A conditional field is a field shown or hidden depending on the values of other fields in the same step. This is different from the condition element of the flow, which decides the steps that come next.

Formity doesn't take care of what's rendered inside a step, so conditional fields aren't a Formity feature. We implement them in the Form component with React Hook Form, but the idea fits any form library.

What a step shows is set in the content prop of Form, a list of items such as input or select. We'll add two items, condition and switch, that render others based on the form values.

The condition item has an if function that receives the form values. If it returns true the items in then are rendered, and otherwise the ones in else.

src/components/form/item/condition.tsx:

TSX
// src/components/form/item/condition.tsx
import { Fragment } from "react";
import { useWatch } from "react-hook-form";

import { ItemView, type Item } from ".";

export interface Condition<T extends Record<string, unknown>> {
  type: "condition";
  if: (values: T) => boolean;
  then: Item<T>[];
  else: Item<T>[];
}

export function ConditionView<T extends Record<string, unknown>>(
  item: Condition<T>,
) {
  const values = useWatch() as T;
  const items = item.if(values) ? item.then : item.else;
  return (
    <>
      {items.map((item, i) => (
        <Fragment key={i}>
          <ItemView {...item} />
        </Fragment>
      ))}
    </>
  );
}

The switch item is the same idea with any number of branches. It renders the items in then of the first branch whose case function returns true, and the ones in default if there is none.

src/components/form/item/switch.tsx:

TSX
// src/components/form/item/switch.tsx
import { Fragment } from "react";
import { useWatch } from "react-hook-form";

import { ItemView, type Item } from ".";

export interface Switch<T extends Record<string, unknown>> {
  type: "switch";
  branches: {
    case: (values: T) => boolean;
    then: Item<T>[];
  }[];
  default: Item<T>[];
}

export function SwitchView<T extends Record<string, unknown>>(item: Switch<T>) {
  const values = useWatch() as T;
  const branch = item.branches.find((branch) => branch.case(values));
  const items = branch ? branch.then : item.default;
  return (
    <>
      {items.map((item, i) => (
        <Fragment key={i}>
          <ItemView {...item} />
        </Fragment>
      ))}
    </>
  );
}

Then, we'll add both items to Item, the union of all item types, and to ItemView, the component that renders each one. Both become generic over the form values, so if and case are typed.

src/components/form/item/index.tsx:

TSX
// src/components/form/item/index.tsx
import { ConditionView, type Condition } from "./condition";
import { SwitchView, type Switch } from "./switch";
import { ColumnsView, type Columns } from "./columns";
import { InputView, type Input } from "./input";
import { NumberView, type Number } from "./number";
import { SelectView, type Select } from "./select";
import { TextareaView, type Textarea } from "./textarea";
import { MultiSelectView, type MultiSelect } from "./multi-select";

export type Item<T extends Record<string, unknown>> =
  | Condition<T>
  | Switch<T>
  | Columns<T>
  | Input
  | Number
  | Select
  | Textarea
  | MultiSelect;

export function ItemView<T extends Record<string, unknown>>(item: Item<T>) {
  switch (item.type) {
    case "condition": {
      return <ConditionView {...item} />;
    }
    case "switch": {
      return <SwitchView {...item} />;
    }
    case "columns": {
      return <ColumnsView {...item} />;
    }
    case "input": {
      return <InputView {...item} />;
    }
    case "number": {
      return <NumberView {...item} />;
    }
    case "select": {
      return <SelectView {...item} />;
    }
    case "textarea": {
      return <TextareaView {...item} />;
    }
    case "multi-select": {
      return <MultiSelectView {...item} />;
    }
  }
}

The columns item contains other items, so it has to be generic as well.

src/components/form/item/columns.tsx:

TSX
// src/components/form/item/columns.tsx
import { ItemView, type Item } from ".";

export interface Columns<T extends Record<string, unknown>> {
  type: "columns";
  columns: Item<T>[];
}

export function ColumnsView<T extends Record<string, unknown>>({
  columns,
}: Columns<T>) {
  return (
    <div className="grid grid-cols-2 gap-3.5">
      {columns.map((item, i) => (
        <ItemView key={i} {...item} />
      ))}
    </div>
  );
}

Finally, in Form the content prop changes from Item[] to Item<T>[].

src/components/form/index.tsx:

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 type { FormStatus } from "@/types/status";

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;
  content: Item<T>[];
  buttons: {
    back: string | null;
    next: string;
  };
  back: Back<T>;
  next: Next<T>;
  status: FormStatus;
}

export function Form<T extends Record<string, unknown>>({
  defaultValues,
  resolver,
  heading,
  content,
  buttons,
  back,
  next,
  status,
}: FormProps<T>) {
  const form = useForm({ defaultValues, resolver });
  return (
    <form
      onSubmit={form.handleSubmit(next)}
      className="flex h-screen w-full items-center justify-center px-4 py-8"
      autoComplete="off"
    >
      <FormProvider {...form}>
        <div className="w-full max-w-md">
          <h2 className="mb-6 text-center text-4xl font-bold text-gray-950">
            {heading}
          </h2>
          <div className="mb-6 flex flex-col gap-4">
            {content.map((field, index) => (
              <ItemView key={index} {...field} />
            ))}
          </div>
          <div className="flex gap-4">
            {buttons.back && (
              <Button
                type="button"
                variant="secondary"
                disabled={status.submitting}
                onClick={() => back(form.getValues())}
              >
                {buttons.back}
              </Button>
            )}
            <Button
              type="submit"
              variant="primary"
              disabled={status.submitting}
            >
              {status.submitting ? "Submitting..." : buttons.next}
            </Button>
          </div>
        </div>
      </FormProvider>
    </form>
  );
}

Use components

Now we'll replace the flow in src/app.tsx with a single step. It asks the user if they are working and, only if so, at what company, using the condition item we created.

Hidden fields keep their value and are still submitted, so all of them still have to be defined in fields. The Zod discriminated union then requires company only when working is "yes".

The variables element that follows creates the values variable, which is the value that we then return. It's a union, so company is only included when working is "yes".

TSX
// src/app.tsx
import { useCallback, useState } from "react";

import {
  Formity,
  type s,
  type Flow,
  type OnReturn,
  type ReturnOutput,
} from "@formity/react";

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

import type { Status, FormStatus } from "./types/status";

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

type Values = WorkingValues | NotWorkingValues;

type WorkingValues = {
  working: "yes";
  company: string;
};

type NotWorkingValues = {
  working: "no";
};

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<{ working: "yes" | "no"; company: string }>,
    s.Variables<{ values: Values }>,
    s.Return<Values>,
  ];
  inputs: Record<never, never>;
  params: {
    status: FormStatus;
  };
};

const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({
        working: ["no", []],
        company: ["", []],
      }),
      render: ({ fields, params, back, next }) => (
        <Form
          key="yourself"
          defaultValues={fields}
          resolver={zodResolver(
            z.discriminatedUnion("working", [
              z.object({
                working: z.literal("yes"),
                company: z.string().min(1, "Required"),
              }),
              z.object({
                working: z.literal("no"),
                company: z.string(),
              }),
            ]),
          )}
          heading="Tell us about yourself"
          content={[
            {
              type: "select",
              name: "working",
              label: "Are you working?",
              placeholder: "Select an option",
              options: [
                { value: "yes", label: "Yes" },
                { value: "no", label: "No" },
              ],
            },
            {
              type: "condition",
              if: ({ working }) => working === "yes",
              then: [
                {
                  type: "input",
                  name: "company",
                  label: "At what company?",
                  placeholder: "Company name",
                },
              ],
              else: [],
            },
          ]}
          buttons={{
            back: null,
            next: "Submit",
          }}
          back={back}
          next={next}
          status={params.status}
        />
      ),
    },
  },
  {
    variables: ({ working, company }) => {
      if (working === "yes") {
        return {
          values: {
            working: "yes",
            company,
          },
        };
      } else {
        return {
          values: {
            working: "no",
          },
        };
      }
    },
  },
  {
    return: ({ values }) => values,
  },
];

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<Schema> flow={flow} params={{ status }} onReturn={onReturn} />
  );
}

When there are more than two cases we can use the switch item instead. In this other version, the user selects a project type and a different field is shown for each one.

The rest works as before. Every field is defined in fields, the Zod union requires only the field of the selected type, and the variables element creates the union that we return.

TSX
// src/app.tsx
import { useCallback, useState } from "react";

import {
  Formity,
  type s,
  type Flow,
  type OnReturn,
  type ReturnOutput,
} from "@formity/react";

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

import type { Status, FormStatus } from "./types/status";

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

type Values = WebsiteValues | MobileValues | OtherValues;

type WebsiteValues = {
  projectType: "website";
  websiteName: string;
};

type MobileValues = {
  projectType: "mobile";
  appName: string;
};

type OtherValues = {
  projectType: "other";
  projectName: string;
};

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<{
      projectType: "website" | "mobile" | "other";
      websiteName: string;
      appName: string;
      projectName: string;
    }>,
    s.Variables<{ values: Values }>,
    s.Return<Values>,
  ];
  inputs: Record<never, never>;
  params: {
    status: FormStatus;
  };
};

const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({
        projectType: ["website", []],
        websiteName: ["", []],
        appName: ["", []],
        projectName: ["", []],
      }),
      render: ({ fields, params, back, next }) => (
        <Form
          key="project"
          defaultValues={fields}
          resolver={zodResolver(
            z.discriminatedUnion("projectType", [
              z.object({
                projectType: z.literal("website"),
                websiteName: z.string().min(1, "Required"),
                appName: z.string(),
                projectName: z.string(),
              }),
              z.object({
                projectType: z.literal("mobile"),
                websiteName: z.string(),
                appName: z.string().min(1, "Required"),
                projectName: z.string(),
              }),
              z.object({
                projectType: z.literal("other"),
                websiteName: z.string(),
                appName: z.string(),
                projectName: z.string().min(1, "Required"),
              }),
            ]),
          )}
          heading="Tell us about your project"
          content={[
            {
              type: "select",
              name: "projectType",
              label: "What type of project are you building?",
              placeholder: "Select a project type",
              options: [
                { value: "website", label: "Website" },
                { value: "mobile", label: "Mobile app" },
                { value: "other", label: "Other" },
              ],
            },
            {
              type: "switch",
              branches: [
                {
                  case: ({ projectType }) => projectType === "website",
                  then: [
                    {
                      type: "input",
                      name: "websiteName",
                      label: "What is the website called?",
                      placeholder: "Website name",
                    },
                  ],
                },
                {
                  case: ({ projectType }) => projectType === "mobile",
                  then: [
                    {
                      type: "input",
                      name: "appName",
                      label: "What is the app called?",
                      placeholder: "App name",
                    },
                  ],
                },
              ],
              default: [
                {
                  type: "input",
                  name: "projectName",
                  label: "What is the project called?",
                  placeholder: "Project name",
                },
              ],
            },
          ]}
          buttons={{
            back: null,
            next: "Submit",
          }}
          back={back}
          next={next}
          status={params.status}
        />
      ),
    },
  },
  {
    variables: ({ projectType, websiteName, appName, projectName }) => {
      if (projectType === "website") {
        return {
          values: {
            projectType: "website",
            websiteName,
          },
        };
      }

      if (projectType === "mobile") {
        return {
          values: {
            projectType: "mobile",
            appName,
          },
        };
      }

      return {
        values: {
          projectType: "other",
          projectName,
        },
      };
    },
  },
  {
    return: ({ values }) => values,
  },
];

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<Schema> flow={flow} params={{ status }} onReturn={onReturn} />
  );
}