Flow elementsCondition

Flow elements

Condition

Learn how the condition element branches the flow based on a condition.


Usage

The condition element branches the flow based on a condition.

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

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

import { WorkingForm } from "./components/working-form";
import { CompanyForm } from "./components/company-form";
import { StudyForm } from "./components/study-form";

type Schema = {
  render: React.ReactNode;
  struct: [
    s.Form<{ working: string }>,
    s.Variables<{ company: string | null }>,
    s.Condition<{
      then: [s.Form<{ company: string }>];
      else: [];
    }>,
    s.Form<{ study: string }>,
    s.Return<{
      working: string;
      company: string | null;
      study: string;
    }>,
  ];
  inputs: Record<never, never>;
  params: Record<never, never>;
};

const flow: Flow<Schema> = [
  {
    form: {
      fields: () => ({ working: ["yes", []] }),
      render: ({ fields, next }) => <WorkingForm fields={fields} next={next} />,
    },
  },
  {
    variables: () => ({ company: null }),
  },
  {
    condition: {
      if: ({ working }) => working === "yes",
      then: [
        {
          form: {
            fields: () => ({ company: ["", []] }),
            render: ({ fields, back, next }) => (
              <CompanyForm fields={fields} back={back} next={next} />
            ),
          },
        },
      ],
      else: [],
    },
  },
  {
    form: {
      fields: () => ({ study: ["business", []] }),
      render: ({ fields, back, next }) => (
        <StudyForm fields={fields} back={back} next={next} />
      ),
    },
  },
  {
    return: ({ working, company, study }) => ({ working, company, study }),
  },
];

export default function App() {
  const onReturn = useCallback<OnReturn<Schema>>((output) => {
    // {
    //   working: string;
    //   company: string | null;
    //   study: string;
    // }
    console.log(output);
  }, []);

  return <Formity<Schema> flow={flow} onReturn={onReturn} />;
}

The if function receives the flow values and returns a boolean. If it is true the elements in then are executed, otherwise the ones in else.

In the Schema, each condition element has an s.Condition entry in struct, with the entries of the elements of then and else.