# Introduction Source: https://formity.app/docs/getting-started/introduction > Define your entire multi-step form as a single, programmable flow. ## What is Formity? Formity is a React library for building multi-step forms as programmable flows that can branch, loop, jump, and track variables across steps, giving you full control over the form's behavior. Fully type-safe and compatible with [React Hook Form](https://react-hook-form.com/), [Formik](https://formik.org/), [TanStack Form](https://tanstack.com/form/latest), and any other form library. It works for onboarding flows, lead capture forms, job applications, and more. Formity only controls the flow between steps. Each step is a React component of your own, so fields, validation, and styling stay in your hands. ## Installation Install version 3 of the package, which works with React 16 or later. ```bash npm install @formity/react ``` ## How it works The core of Formity is the flow, an array of elements that each define a piece of the multi-step form's behavior. By combining them, you can build any multi-step form you can imagine. The example below asks whether the user is a software developer and, only if they are, asks for their favorite programming language. At the end, it returns both answers. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { SoftwareDeveloperForm } from "./components/software-developer-form"; import { LanguageForm } from "./components/language-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ softwareDeveloper: string }>, s.Variables<{ language: string | null }>, s.Condition<{ then: [s.Form<{ language: string }>]; else: []; }>, s.Return<{ softwareDeveloper: string; language: string | null }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ softwareDeveloper: ["yes", []] }), render: ({ fields, next }) => ( ), }, }, { variables: () => ({ language: null }), }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ language: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, { return: ({ softwareDeveloper, language }) => ({ softwareDeveloper, language, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // softwareDeveloper: string; // language: string | null; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` These are the pieces involved: - **Flow**: Defines the structure and behavior of the multi-step form. Its elements run in order, and the flow pauses at each `form` element until the user submits that step. - **Flow values**: An object made available to each element as the flow progresses. It contains the values from the form and variables elements encountered so far. - **Schema**: The type of the flow. Its `struct` property lists the same elements as the flow, which keeps the flow values and the returned values type-safe. - **Formity**: The component that renders the multi-step form from the flow. When the steps need to render something other than a `ReactNode`, use the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook instead. - **onReturn**: A callback function that is called when the form is completed. It receives the values returned by the `return` element, which is where you would submit them. ### Form steps In a `form` element, the `fields` function gives each field a default value and an array. Values the user already entered are kept unless the array changes. The `render` function renders the step with a component that you write. The component receives the default values in `fields` and moves through the flow by calling `next` or `back` with its values. ```tsx // src/components/language-form.tsx import { useState } from "react"; import type { Back, Next } from "@formity/react"; type Values = { language: string }; type LanguageFormProps = { fields: Values; back: Back; next: Next; }; export function LanguageForm({ fields, back, next }: LanguageFormProps) { const [language, setLanguage] = useState(fields.language); return (
{ event.preventDefault(); next({ language }); }} > setLanguage(event.target.value)} />
); } ``` This example uses React state to stay simple. In practice a form library takes care of the state and the validation of each step. See how it is done with [React Hook Form](https://formity.app/docs/use-with-form-libraries/react-hook-form.md), [Formik](https://formity.app/docs/use-with-form-libraries/formik.md), and [TanStack Form](https://formity.app/docs/use-with-form-libraries/tanstack-form.md). ### Flow elements Each element is an object with a single key that tells which element it is. - [`form`](https://formity.app/docs/flow-elements/form.md): Shows a step and adds its values to the flow values. - [`return`](https://formity.app/docs/flow-elements/return.md): Ends the form and passes values to `onReturn`. - [`variables`](https://formity.app/docs/flow-elements/variables.md): Adds computed values to the flow values. - [`condition`](https://formity.app/docs/flow-elements/condition.md): Branches into `then` or `else` depending on `if`. - [`switch`](https://formity.app/docs/flow-elements/switch.md): Branches into the first `case` that is true, or into `default`. - [`jump`](https://formity.app/docs/flow-elements/jump.md): Marks a form that can be jumped to from anywhere in the flow. - [`loop`](https://formity.app/docs/flow-elements/loop.md): Repeats the elements in `do` while `while` is true. - [`yield`](https://formity.app/docs/flow-elements/yield.md): Passes values to `onYield` when the user moves between steps. - [`module`](https://formity.app/docs/flow-elements/module.md): Includes a nested flow that can be defined in another file. ## Next steps Follow the **[Tutorial](https://formity.app/docs/getting-started/tutorial.md)** to build a multi-step form with conditional logic from scratch. # Tutorial Source: https://formity.app/docs/getting-started/tutorial > Follow this tutorial to grasp the core concepts of Formity and how it has to be used. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## Initial steps We'll show you how to turn a single-step form into a dynamic multi-step form with conditional logic. The starting point is already set up in the GitHub repo below, so go ahead and clone it to follow along. ```bash git clone https://github.com/martiserra99/formity-tutorial ``` Make sure you run the following command to install all the dependencies. ```bash npm install ``` Then, start the development server. ```bash npm run dev ``` The repo is a React project using Vite and TypeScript, with `@formity/react` already installed. ## Single-step form If you take a look at the `src/app.tsx` file, you'll find a single-step form already in place. This form is built using [React Hook Form](https://react-hook-form.com/). However, you're not restricted to this library. Formity is designed to work smoothly with any single-step form library you choose. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Form } from "./components/form"; import { Output } from "./components/output"; type Values = { name: string; surname: string; age: number }; export default function App() { const [output, setOutput] = useState(null); const onSubmit = useCallback((output: Values) => { setOutput(output); }, []); if (output) { return setOutput(null)} />; } return (
); } ``` The `Form` component used above is defined in `src/components/form/index.tsx`. It's a thin wrapper around React Hook Form that renders the heading, the fields and the submit button. ```tsx // src/components/form/index.tsx import type { DefaultValues, Resolver } from "react-hook-form"; import { useForm, FormProvider } from "react-hook-form"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; interface FormProps> { defaultValues: DefaultValues; resolver: Resolver; heading: string; content: Item[]; submit: string; onSubmit: (fields: T) => void; } export function Form>({ defaultValues, resolver, heading, content, submit, onSubmit, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{content.map((field, index) => ( ))}
); } ``` The repo also includes the other components used in this tutorial, like `Output`, which displays the submitted values, and `Done`, which displays a thank you screen. We won't change them. ## Multi-step form To get started with Formity, the first thing we'll do is use the `Formity` component. It is the one that renders the multi-step form, and these are the most important props: - `flow`: Defines the structure and behavior of the multi-step form. - `onReturn`: A callback function that is triggered when the form is completed. We'll replace the code that we have in `src/app.tsx` with the following code. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import { Output } from "./components/output"; type Schema = { render: React.ReactNode; struct: []; inputs: Record; params: Record; }; const flow: Flow = []; export default function App() { const [output, setOutput] = useState | null>(null); const onReturn = useCallback>((output) => { setOutput(output); }, []); if (output) { return setOutput(null)} />; } return flow={flow} onReturn={onReturn} />; } ``` The `Schema` type is what ensures complete type safety. Its `struct` property describes the flow element by element. The rest of the properties are explained in [useFormity](https://formity.app/docs/basic-concepts/use-formity.md). The next step is to create the flow, which defines the structure and behavior of the multi-step form. We'll do this by writing the following code. ```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 { Form } from "./components/form"; import { Output } from "./components/output"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Form<{ softwareDeveloper: string }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, next }) => (
), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, next }) => ( ), }, }, ]; export default function App() { const [output, setOutput] = useState | null>(null); const onReturn = useCallback>((output) => { setOutput(output); }, []); if (output) { return setOutput(null)} />; } return flow={flow} onReturn={onReturn} />; } ``` The `flow` constant is an array of type `Flow`. There are different types of elements you can use within the flow, and in this example, we've included two [form](https://formity.app/docs/flow-elements/form.md) elements. Each one defines a step, and it is described in the `Schema` with `s.Form`, which receives the type of the values of that step. A form element has these properties: - `fields`: Returns the default values, each as a tuple of the value and an array. Values entered by the user are kept while the array is unchanged. - `render`: Renders the step. It receives the default values as `fields` and a `next` function that takes the form values and goes to the next step. Note that each `Form` has a different `key`. Every step renders the same component, so without it React would reuse the component from the previous step and React Hook Form would keep its state instead of starting with the new default values. As the flow progresses, the values of each form are collected in an object called the **flow values**, which is made available to the elements that come next. If you complete the multi-step form, nothing happens, because `onReturn` is only called when the flow reaches a [return](https://formity.app/docs/flow-elements/return.md) element. Let's add one, as shown below. ```diff // src/app.tsx @@ -19,6 +19,12 @@ struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Form<{ softwareDeveloper: string }>, + s.Return<{ + name: string; + surname: string; + age: number; + softwareDeveloper: string; + }>, ]; inputs: Record; params: Record; @@ -108,6 +114,14 @@ ), }, }, + { + return: ({ name, surname, age, softwareDeveloper }) => ({ + name, + surname, + age, + softwareDeveloper, + }), + }, ]; export default function App() { ``` The return element defines what the multi-step form returns. It receives the flow values, and the values it returns are passed to `onReturn`. In the `Schema`, it is typed with `s.Return`. So far, we've covered the form and return elements. However, Formity supports additional elements that allow you to build any logic you need. One of these is the [condition](https://formity.app/docs/flow-elements/condition.md), which can be used like this. ```diff // src/app.tsx @@ -19,11 +19,27 @@ struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Form<{ softwareDeveloper: string }>, - s.Return<{ - name: string; - surname: string; - age: number; - 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; @@ -115,12 +131,99 @@ }, }, { - return: ({ name, surname, age, softwareDeveloper }) => ({ - name, - surname, - age, - softwareDeveloper, - }), + condition: { + if: ({ softwareDeveloper }) => softwareDeveloper === "yes", + then: [ + { + form: { + fields: () => ({ + expertise: ["", []], + }), + render: ({ fields, next }) => ( + + ), + }, + }, + { + return: ({ name, surname, age, expertise }) => ({ + name, + surname, + age, + softwareDeveloper: true, + expertise, + }), + }, + ], + else: [ + { + form: { + fields: () => ({ + interested: ["", []], + }), + render: ({ fields, next }) => ( + + ), + }, + }, + { + return: ({ name, surname, age, interested }) => ({ + name, + surname, + age, + softwareDeveloper: false, + interested, + }), + }, + ], + }, }, ]; ``` The condition element branches the flow. Its `if` function receives the flow values and determines whether `then` or `else` is executed. Here, each branch has its own form and return. The user should also be able to go back to previous steps. Along with `next`, the `render` function receives `back`, which takes the form values and goes to the previous step. We'll update the `Form` component to use it, as shown below. The `submit` and `onSubmit` props are replaced with `buttons`, `back` and `next`. ```diff // src/components/form/index.tsx @@ -1,4 +1,5 @@ import type { DefaultValues, Resolver } from "react-hook-form"; +import type { Back, Next } from "@formity/react"; import { useForm, FormProvider } from "react-hook-form"; @@ -10,8 +11,12 @@ resolver: Resolver; heading: string; content: Item[]; - submit: string; - onSubmit: (fields: T) => void; + buttons: { + back: string | null; + next: string; + }; + back: Back; + next: Next; } export function Form>({ @@ -19,13 +24,14 @@ resolver, heading, content, - submit, - onSubmit, + buttons, + back, + next, }: FormProps) { const form = useForm({ defaultValues, resolver }); return ( @@ -40,8 +46,17 @@ ))}
+ {buttons.back && ( + + )}
``` Then, we need to update the flow as shown below, so that every form receives `back` and `next`. The first step has no back button since there's no previous step. ```diff // src/app.tsx @@ -54,7 +54,7 @@ surname: ["", []], age: [20, []], }), - render: ({ fields, next }) => ( + render: ({ fields, back, next }) => ( ), }, @@ -102,7 +106,7 @@ fields: () => ({ softwareDeveloper: ["", []], }), - render: ({ fields, next }) => ( + render: ({ fields, back, next }) => ( ), }, @@ -139,7 +147,7 @@ fields: () => ({ expertise: ["", []], }), - render: ({ fields, next }) => ( + render: ({ fields, back, next }) => ( ), }, @@ -184,7 +196,7 @@ fields: () => ({ interested: ["", []], }), - render: ({ fields, next }) => ( + render: ({ fields, back, next }) => ( ), }, ``` ## Submit form Until now, we have shown the values we want to submit. Now, we need to create the logic to submit these values and keep track of the submission state. To do this, we'll start by creating a `src/types/status.ts` file with the following code. ```ts // src/types/status.ts export type Status = FormStatus | DoneStatus; export type FormStatus = { type: "form"; submitting: boolean; }; export type DoneStatus = { type: "done"; }; ``` Then, we'll update the `src/app.tsx` file to include the submission logic and display a thank you screen once the values are submitted, replacing `Output` with `Done`. ```diff // src/app.tsx @@ -1,18 +1,14 @@ import { useCallback, useState } from "react"; -import { - Formity, - type s, - type Flow, - type OnReturn, - type ReturnOutput, -} from "@formity/react"; +import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; +import type { Status } from "./types/status"; + import { Form } from "./components/form"; -import { Output } from "./components/output"; +import { Done } from "./components/done"; type Schema = { render: React.ReactNode; @@ -244,14 +240,29 @@ ]; export default function App() { - const [output, setOutput] = useState | null>(null); + const [status, setStatus] = useState({ + type: "form", + submitting: false, + }); - const onReturn = useCallback>((output) => { - setOutput(output); + const onReturn = useCallback>(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" }); }, []); - if (output) { - return setOutput(null)} />; + if (status.type === "done") { + return ( + setStatus({ type: "form", submitting: false })} + /> + ); } return flow={flow} onReturn={onReturn} />; ``` As you may have noticed, the form stays interactive during submission, with no feedback shown. To address this, we'll access the `status` object within the `Form` to disable the buttons and provide feedback to the user. ```diff // src/components/form/index.tsx @@ -3,6 +3,8 @@ import { useForm, FormProvider } from "react-hook-form"; +import type { FormStatus } from "@/types/status"; + import { ItemView, type Item } from "./item"; import { Button } from "../button"; @@ -17,6 +19,7 @@ }; back: Back; next: Next; + status: FormStatus; } export function Form>({ @@ -27,6 +30,7 @@ buttons, back, next, + status, }: FormProps) { const form = useForm({ defaultValues, resolver }); return ( @@ -50,12 +54,17 @@ )} - ``` Then, we'll pass the `status` object to the flow so that we can provide it to each `Form`. We'll do this with the [`params`](https://formity.app/docs/basic-concepts/params.md) prop of the `Formity` component. Its shape is defined in the `Schema`, and its values are received by the `render` function. This is the final version of the `src/app.tsx` file. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type s, type Flow, type OnReturn } 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState({ type: "form", submitting: false, }); const onReturn = useCallback>(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" }); }, []); if (status.type === "done") { return ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` Unlike the flow values, params are not part of the flow logic. They exist solely for rendering, so they are only available in the `render` function, and any changes to them are immediately reflected in the form. That's why the buttons are disabled as soon as `status.submitting` becomes `true`. ## Next steps Continue with **[Basic concepts](https://formity.app/docs/basic-concepts/use-formity.md)** to learn the core building blocks of Formity. Then, explore the rest of the **[Flow elements](https://formity.app/docs/flow-elements/form.md)**, like variables and loops, and the **[Guides](https://formity.app/docs/guides/animating-forms.md)** for common use cases. # Building with AI Source: https://formity.app/docs/getting-started/building-with-ai > Learn how to give the Formity documentation to AI tools so they can help you build your forms. ## Help AI know Formity AI tools like Claude Code, Cursor and ChatGPT may not know Formity, or only know a previous version. For accurate answers, give them the documentation, available as markdown in three ways. ## Using llms.txt The [llms.txt](https://formity.app/llms.txt) file is an index of the documentation. It lists every page with a short description of what it covers and a link to its markdown version. ```text https://formity.app/llms.txt ``` It is the file you will use the most, since the AI tool can find and read only the pages it needs. ```text Read https://formity.app/llms.txt and build a multi-step form with Formity and React Hook Form. The first step asks for the name and the email, the second for the job title and the company, and the third for the country and the city. The last step is a review step that shows all the answers, with an edit button next to each one to jump back to its step. ``` ## Using llms-full.txt The [llms-full.txt](https://formity.app/llms-full.txt) file contains the entire documentation in a single file. ```text https://formity.app/llms-full.txt ``` Use it when you want the AI tool to understand everything about Formity before it starts on your form. It is a large file, so make sure it fits in the tool's context. ```text Read https://formity.app/llms-full.txt and build an event registration form with Formity and TanStack Form. Ask for the company details only when the user registers as a business, and repeat the attendee details step for each ticket. Add a sidebar to go back to any completed step and animate the transitions between steps. ``` ## Using specific pages Every page of the documentation is also available as markdown. To get it, add `.md` to its URL. ```text https://formity.app/docs/guides/review-step.md ``` Use it when a single page is enough. ```text Read https://formity.app/docs/guides/review-step.md and add a review step at the end of my form, with an edit button next to each answer to jump back to its step. ``` # useFormity Source: https://formity.app/docs/basic-concepts/use-formity > Everything you need to know about the useFormity hook. ## useFormity The `useFormity` hook is the main hook of this package. It returns what the current step's `render` function returns, which unlike the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component doesn't have to be a `ReactNode`. It receives an object with these properties: - [`flow`](https://formity.app/docs/basic-concepts/flow.md): Defines the structure and behavior of the multi-step form (required). - [`inputs`](https://formity.app/docs/basic-concepts/inputs.md): Defines values that can be used within the flow. - [`params`](https://formity.app/docs/basic-concepts/params.md): Defines values that can be used when rendering each form. - [`history`](https://formity.app/docs/basic-concepts/history.md): A boolean to track previous states for back navigation (defaults to true). - [`initialState`](https://formity.app/docs/basic-concepts/state.md): The state to resume the multi-step form from, of type `State`. - [`onYield`](https://formity.app/docs/flow-elements/yield.md): A callback function of type `OnYield` that is triggered when values are yielded. It receives the yielded values. - [`onReturn`](https://formity.app/docs/flow-elements/return.md): A callback function of type `OnReturn` that is triggered when the form completes. It receives the returned values. It also takes a `Schema` type with these properties: - `render`: The type each form step renders, which is what the hook returns. - `struct`: The elements of the flow and their values. - `inputs`: The type of the `inputs` property. - `params`: The type of the `params` property. Here's an example where each step renders its step number along with the form. ```tsx import { useCallback, type ReactNode } from "react"; import { useFormity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: { step: number; form: ReactNode }; struct: [s.Form<{ name: string }>, s.Return<{ name: string }>]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], }), render: ({ fields, next }) => ({ step: 0, form: , }), }, }, { return: ({ name }) => ({ name }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // } console.log(output); }, []); const { step, form } = useFormity({ flow, onReturn }); return (

Step {step + 1}

{form}
); } ``` # Formity Source: https://formity.app/docs/basic-concepts/formity > Everything you need to know about the Formity component. ## Formity The `Formity` component is the main component of this package. It renders the current step of the multi-step form. To render something other than a `ReactNode`, use the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook instead. It receives these props: - [`flow`](https://formity.app/docs/basic-concepts/flow.md): Defines the structure and behavior of the multi-step form (required). - [`inputs`](https://formity.app/docs/basic-concepts/inputs.md): Defines values that can be used within the flow. - [`params`](https://formity.app/docs/basic-concepts/params.md): Defines values that can be used when rendering each form. - [`history`](https://formity.app/docs/basic-concepts/history.md): A boolean to track previous states for back navigation (defaults to true). - [`initialState`](https://formity.app/docs/basic-concepts/state.md): The state to resume the multi-step form from, of type `State`. - [`onYield`](https://formity.app/docs/flow-elements/yield.md): A callback function of type `OnYield` that is triggered when values are yielded. It receives the yielded values. - [`onReturn`](https://formity.app/docs/flow-elements/return.md): A callback function of type `OnReturn` that is triggered when the form completes. It receives the returned values. It also takes a `Schema` type with these properties: - `render`: The type each form step renders, which must be `ReactNode`. - `struct`: The elements of the flow and their values. - `inputs`: The type of the `inputs` prop. - `params`: The type of the `params` prop. In the following example the form has a single step and returns the name. ```tsx import { useCallback, type ReactNode } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: ReactNode; struct: [s.Form<{ name: string }>, s.Return<{ name: string }>]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], }), render: ({ fields, next }) => , }, }, { return: ({ name }) => ({ name }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` # Flow Source: https://formity.app/docs/basic-concepts/flow > Learn what the flow is about and how it can be used to define the forms. ## Flow The flow is used to define the structure and behavior of the multi-step form. It is an array of different elements, and the existing ones are as follows: - [**Form**](https://formity.app/docs/flow-elements/form.md): Defines a step in the form. - [**Return**](https://formity.app/docs/flow-elements/return.md): Defines what the form returns. - [**Variables**](https://formity.app/docs/flow-elements/variables.md): Adds variables to the flow values. - [**Condition**](https://formity.app/docs/flow-elements/condition.md): Branches the flow based on a condition. - [**Switch**](https://formity.app/docs/flow-elements/switch.md): Branches the flow into the first case that is `true`. - [**Jump**](https://formity.app/docs/flow-elements/jump.md): Defines a form that can be jumped to from anywhere. - [**Loop**](https://formity.app/docs/flow-elements/loop.md): Repeats elements while a condition is `true`. - [**Yield**](https://formity.app/docs/flow-elements/yield.md): Yields values when navigating between steps. - [**Module**](https://formity.app/docs/flow-elements/module.md): Includes a nested flow defined elsewhere. The elements run in order, and the values collected along the way, known as the **flow values**, are made available to the elements that follow. By combining these elements, we can create advanced multi-step forms with complex logic. Here's a simple example with two form steps and a return. ```tsx import { useCallback, type ReactNode } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; import { SoftwareDeveloperForm } from "./components/software-developer-form"; type Schema = { render: ReactNode; struct: [ s.Form<{ name: string; surname: string }>, s.Form<{ softwareDeveloper: string }>, s.Return<{ name: string; surname: string; softwareDeveloper: string }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []] }), render: ({ fields, next }) => , }, }, { form: { fields: () => ({ softwareDeveloper: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ name, surname, softwareDeveloper }) => ({ name, surname, softwareDeveloper, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // surname: string; // softwareDeveloper: string; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The flow is of type `Flow`, which accepts a `Schema` type that ensures complete type safety across all steps. The `Schema` has these properties: - `render`: The type each form step renders. It must be `ReactNode` with the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component, and can be any type with the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook. - `struct`: The elements of the flow and their values, listed in the same order as in the flow. - `inputs`: The type of the [`inputs`](https://formity.app/docs/basic-concepts/inputs.md) prop. - `params`: The type of the [`params`](https://formity.app/docs/basic-concepts/params.md) prop. In each form element, `fields` defines the default values and `render` renders the step, which moves through the flow by calling `next` or `back` with its values. Both are explained in the [form](https://formity.app/docs/flow-elements/form.md) element. # Inputs Source: https://formity.app/docs/basic-concepts/inputs > Learn how to pass values to be used inside the flow. ## Inputs As the flow progresses, an object called the **flow values** is made available to each element. It contains the values collected from [form](https://formity.app/docs/flow-elements/form.md) elements and [variables](https://formity.app/docs/flow-elements/variables.md) elements encountered so far. To include additional values from the start, pass them as `inputs` to the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component or the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook. Their type is defined by the `inputs` property of the `Schema`. In the following example, `languages` and `defaultLanguage` are inputs. ```tsx import { useCallback, type ReactNode } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { LanguageForm } from "./components/language-form"; type Schema = { render: ReactNode; struct: [s.Form<{ language: string }>, s.Return<{ language: string }>]; inputs: { languages: { label: string; value: string }[]; defaultLanguage: string; }; params: Record; }; const flow: Flow = [ { form: { fields: ({ defaultLanguage }) => ({ language: [defaultLanguage, []], }), render: ({ fields, values, back, next }) => ( ), }, }, { return: ({ language }) => ({ language }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // language: string; // } console.log(output); }, []); return ( flow={flow} inputs={{ languages: [ { label: "English", value: "en" }, { label: "Spanish", value: "es" }, { label: "Catalan", value: "ca" }, ], defaultLanguage: "en", }} onReturn={onReturn} /> ); } ``` There are a few things to keep in mind: - Inputs are only read when the form starts. Changing them afterwards has no effect, and they are ignored when an [`initialState`](https://formity.app/docs/basic-concepts/state.md) is provided. - A value collected later in the flow with the same name as an input replaces it. This makes inputs useful for providing defaults, as shown in the [jump](https://formity.app/docs/flow-elements/jump.md) element. - For values that are only needed when rendering and that should update the form when they change, use [`params`](https://formity.app/docs/basic-concepts/params.md) instead. # Params Source: https://formity.app/docs/basic-concepts/params > Learn how to pass values that can be used when rendering each form. ## Params Pass `params` to the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component or the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook to provide values for rendering each form step. Their type is defined by the `params` property of the `Schema`. In the following example, `heading` is a param, while `languages` and `defaultLanguage` are inputs. ```tsx import { useCallback, type ReactNode } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { LanguageForm } from "./components/language-form"; type Schema = { render: ReactNode; struct: [s.Form<{ language: string }>, s.Return<{ language: string }>]; inputs: { languages: { label: string; value: string }[]; defaultLanguage: string; }; params: { heading: string; }; }; const flow: Flow = [ { form: { fields: ({ defaultLanguage }) => ({ language: [defaultLanguage, []], }), render: ({ fields, values, params, back, next }) => ( ), }, }, { return: ({ language }) => ({ language }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // language: string; // } console.log(output); }, []); return ( flow={flow} inputs={{ languages: [ { label: "English", value: "en" }, { label: "Spanish", value: "es" }, { label: "Catalan", value: "ca" }, ], defaultLanguage: "en", }} params={{ heading: "What language do you speak the most?", }} onReturn={onReturn} /> ); } ``` There are a few things to keep in mind: - Params are not part of the flow values, only available in the `render` function of [form](https://formity.app/docs/flow-elements/form.md) elements. - Changes to params are reflected immediately, so the current step re-renders with the new values. This makes them useful for values that can change while the form is in progress. - For values that are needed in the logic of the flow, such as in conditions or default field values, use [`inputs`](https://formity.app/docs/basic-concepts/inputs.md) instead, which are part of the flow values. # History Source: https://formity.app/docs/basic-concepts/history > Learn how the history prop controls back navigation in the form. ## History Pass `history` to the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component or the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook to control whether Formity tracks the steps the user has visited. It is a boolean that defaults to `true`. When it is `true`, `back` returns to the step the user was on before, including the step they jumped from. This is the right choice when users move through the form with `next` and `back`. When it is `false`, only the current step is kept, so `back` stays on the current step. Use it when navigation is handled with the [jump](https://formity.app/docs/flow-elements/jump.md) element instead, as in the following example. ```tsx import { useCallback, type ReactNode } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { NameForm } from "./components/name-form"; import { EmailForm } from "./components/email-form"; type Schema = { render: ReactNode; struct: [ s.Jump>, s.Jump>, s.Return<{ name: string; email: string }>, ]; inputs: { name: string; email: string; }; params: Record; }; const flow: Flow = [ { jump: { id: "name", at: { form: { fields: ({ name }) => ({ name: [name, []] }), render: ({ fields, next, jump }) => ( ), }, }, }, }, { jump: { id: "email", at: { form: { fields: ({ email }) => ({ email: [email, []] }), render: ({ fields, next, jump }) => ( ), }, }, }, }, { return: ({ name, email }) => ({ name, email }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // email: string; // } console.log(output); }, []); return ( flow={flow} inputs={{ name: "", email: "" }} history={false} onReturn={onReturn} /> ); } ``` # State Source: https://formity.app/docs/basic-concepts/state > Learn what the state is about and how it can be used. ## Overview At any moment, a multi-step form has a state. It records which step the user is on, how they got there, and what they entered in every step so far. You can read the state, store it wherever you like, and hand it back to Formity later so the user picks up the form exactly where they left it. There are three parts to the API: - `getState`: A function received by the form element's [`render`](https://formity.app/docs/flow-elements/form.md) function. It takes the current step's form values and returns the state of the multi-step form, without changing anything. - `setState`: A function received by the form element's [`render`](https://formity.app/docs/flow-elements/form.md) function. It takes a `State` and replaces the state of the multi-step form with it. - `initialState`: A value you can pass to the [`Formity`](https://formity.app/docs/basic-concepts/formity.md) component or the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook. The multi-step form starts from this state instead of from the first step. The state is of type `State`, and the two functions are of type `GetState` and `SetState`. You don't need to know what the state looks like inside. Get it from `getState`, store it, and pass it back unchanged. Two things to keep in mind: - The state can be stored with `JSON.stringify` as long as the flow values are JSON-serializable. Values such as `Date` or `File` need to be converted by you. - A saved state only works with the flow it was created from. If the flow changes between saving and resuming, discard the saved state. ## Saving the state To save the state as the user fills out the form, call `getState` inside your form component and persist it whenever the values change. Using React Hook Form, it could look like this: ```tsx const onSaveState = useEffectEvent(({ values }: { values: Values }) => { const state = getState(values); saveState(state); }); useEffect(() => { const unsubscribe = form.subscribe({ formState: { values: true }, callback: onSaveState, }); onSaveState({ values: form.getValues() }); return () => unsubscribe(); }, [form]); ``` In this example, `form` comes from React Hook Form's `useForm` hook and `Values` is the type of the form values. The `saveState` function is not part of Formity. You write it yourself to store the state wherever you want, such as `localStorage` or a database. ## Resuming the state Pass the saved state to the `initialState` prop to resume the form from where the user left off. ```tsx return ( flow={flow} initialState={savedState} onReturn={onReturn} /> ); ``` # Form Source: https://formity.app/docs/flow-elements/form > Learn how the form element defines a step, its default values, and how it is rendered. ## Usage The **form** element defines a step in the multi-step form. The flow pauses at it until the user submits the step, and the submitted values are added to the flow values. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Return<{ name: string; surname: string; age: number }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, next }) => , }, }, { return: ({ name, surname, age }) => ({ name, surname, age }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // surname: string; // age: number; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The step is rendered by the `AboutMeForm` component, which receives the default values in `fields` and calls `next` with its values when the form is submitted. ```tsx // src/components/about-me-form.tsx import { useState } from "react"; import type { Next } from "@formity/react"; type Values = { name: string; surname: string; age: number }; type AboutMeFormProps = { fields: Values; next: Next; }; export function AboutMeForm({ fields, next }: AboutMeFormProps) { const [name, setName] = useState(fields.name); const [surname, setSurname] = useState(fields.surname); const [age, setAge] = useState(fields.age); return ( { event.preventDefault(); next({ name, surname, age }); }} > setName(event.target.value)} /> setSurname(event.target.value)} /> setAge(Number(event.target.value))} /> ); } ``` In the `Schema`, each form element has an `s.Form` entry in `struct`. Its type must match the fields returned by `fields` and the values passed to `next`. This example uses React state to stay simple. In practice a form library takes care of the state and the validation of each step. See how it is done with [React Hook Form](https://formity.app/docs/use-with-form-libraries/react-hook-form.md), [Formik](https://formity.app/docs/use-with-form-libraries/formik.md), and [TanStack Form](https://formity.app/docs/use-with-form-libraries/tanstack-form.md). ## Fields The `fields` function receives the flow values, which are the [`inputs`](https://formity.app/docs/basic-concepts/inputs.md) and the values collected so far from previous form and [variables](https://formity.app/docs/flow-elements/variables.md) elements in the flow. It returns a default value and an array for each field. When the user returns to the step, each entered value is kept unless its array has changed. Leave the arrays empty unless the form is in a [loop](https://formity.app/docs/flow-elements/loop.md). ```tsx fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), ``` ## Render The `render` function renders the form step. It receives an object with the following properties: - `fields`: The default values of the form. - `values`: The flow values. - `params`: The values passed with the [`params`](https://formity.app/docs/basic-concepts/params.md) prop. - `next(values)`: Receives the form values and goes to the next step. - `back(values)`: Receives the form values and goes to the previous step. - `jump(id, values)`: Receives a [jump](https://formity.app/docs/flow-elements/jump.md) element's `id` and the form values, and goes to it. - `getState(values)`: Receives the form values and returns the [state](https://formity.app/docs/basic-concepts/state.md) of the multi-step form. - `setState(state)`: Receives a [state](https://formity.app/docs/basic-concepts/state.md) and replaces the state of the multi-step form with it. ```tsx render: ({ fields, next }) => ( ), ``` To pass these functions as props, type them with `Next`, `Back`, `Jump`, `GetState`, and `SetState`. ```tsx import type { Next, Back, Jump } from "@formity/react"; type Values = { name: string; surname: string; age: number }; type AboutMeFormProps = { fields: Values; next: Next; back: Back; jump: Jump; }; ``` # Return Source: https://formity.app/docs/flow-elements/return > Learn how the return element ends the flow and passes its values to the `onReturn` callback. ## Usage The **return** element defines what the multi-step form returns. When the flow reaches it, the `onReturn` callback is called with the returned values and the flow ends. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Return<{ fullName: string; age: number }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, next }) => , }, }, { return: ({ name, surname, age }) => ({ fullName: `${name} ${surname}`, age, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // fullName: string; // age: number; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The `return` function receives the flow values and returns the values passed to `onReturn`. Its return type must match the `s.Return` entry in `struct`. The `OnReturn` type is the type of the `onReturn` callback, and `ReturnOutput` is the type of the values it receives. ## Ending the flow The return element is not a step, so it renders nothing. After `onReturn` is called, the multi-step form keeps rendering the last form, so use `onReturn` to submit the values and show something else. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type s, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Return<{ fullName: string; age: number }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, next }) => , }, }, { return: ({ name, surname, age }) => ({ fullName: `${name} ${surname}`, age, }), }, ]; export default function App() { const [output, setOutput] = useState | null>(null); const onReturn = useCallback>((output) => { setOutput(output); }, []); if (output) { return

Thank you, {output.fullName}!

; } return flow={flow} onReturn={onReturn} />; } ``` ## Skipped forms A form inside a [condition](https://formity.app/docs/flow-elements/condition.md), [switch](https://formity.app/docs/flow-elements/switch.md) or [loop](https://formity.app/docs/flow-elements/loop.md) may be skipped, so its values aren't available outside it. To use them in a return, define them first with a [variables](https://formity.app/docs/flow-elements/variables.md) element, which the form replaces when reached. ```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"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ working: boolean }>, s.Variables<{ company: string | null }>, s.Condition<{ then: [s.Form<{ company: string }>]; else: []; }>, s.Return<{ working: boolean; company: string | null }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ working: [true, []] }), render: ({ fields, next }) => , }, }, { variables: () => ({ company: null }), }, { condition: { if: ({ working }) => working, then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, { return: ({ working, company }) => ({ working, company }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // working: boolean; // company: string | null; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` ## Multiple returns Instead of a single return element at the end, each branch can end with its own, and only the one that is reached is executed. ```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"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ working: boolean }>, s.Condition<{ then: [ s.Form<{ company: string }>, s.Return<{ working: true; company: string }>, ]; else: [s.Return<{ working: false }>]; }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ working: [true, []] }), render: ({ fields, next }) => , }, }, { condition: { if: ({ working }) => working, then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ company }) => ({ working: true, company }), }, ], else: [ { return: () => ({ working: false }), }, ], }, }, ]; export default function App() { const onReturn = useCallback>((output) => { // | { // working: true; // company: string; // } // | { // working: false; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` Here `onReturn` receives the union of the types of all the return elements. # Variables Source: https://formity.app/docs/flow-elements/variables > Learn how the variables element adds values to the flow values. ## Usage The **variables** element defines variables that are added to the flow values. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { AboutMeForm } from "./components/about-me-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ name: string; surname: string; age: number }>, s.Variables<{ fullName: string }>, s.Return<{ fullName: string; age: number }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, next }) => , }, }, { variables: ({ name, surname }) => ({ fullName: `${name} ${surname}`, }), }, { return: ({ fullName, age }) => ({ fullName, age }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // fullName: string; // age: number; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The `variables` function receives the flow values, which are the [`inputs`](https://formity.app/docs/basic-concepts/inputs.md) and the values from previous [form](https://formity.app/docs/flow-elements/form.md) and variables elements. It returns the variables to add for the elements that follow. In the `Schema`, each variables element has an `s.Variables` entry in `struct`. Its type must match the object returned by `variables`. The `variables` function runs every time the flow reaches it, so it must be synchronous and free of side effects. If the flow needs fetched data, fetch it beforehand and pass it as [`inputs`](https://formity.app/docs/basic-concepts/inputs.md). ## Replacing values The variables are merged into the flow values. If a variable has the same name as an existing value, it replaces that value for the elements that follow. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { EmailForm } from "./components/email-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ email: string }>, s.Variables<{ email: string }>, s.Return<{ email: string }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ email: ["", []] }), render: ({ fields, next }) => , }, }, { variables: ({ email }) => ({ email: email.trim().toLowerCase() }), }, { return: ({ email }) => ({ email }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // email: string; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` ## Skipped forms A form inside a [condition](https://formity.app/docs/flow-elements/condition.md), [switch](https://formity.app/docs/flow-elements/switch.md) or [loop](https://formity.app/docs/flow-elements/loop.md) may be skipped, so its values aren't available outside it. To use them in a [return](https://formity.app/docs/flow-elements/return.md), define them first with a variables element, which the form replaces when reached. ```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"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ working: boolean }>, s.Variables<{ company: string | null }>, s.Condition<{ then: [s.Form<{ company: string }>]; else: []; }>, s.Return<{ working: boolean; company: string | null }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ working: [true, []] }), render: ({ fields, next }) => , }, }, { variables: () => ({ company: null }), }, { condition: { if: ({ working }) => working, then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, { return: ({ working, company }) => ({ working, company }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // working: boolean; // company: string | null; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The same applies to a variables element inside a condition, switch or loop. Its variables can only be used inside it, so define them before it if later elements need them. ## Variables in loops In a [loop](https://formity.app/docs/flow-elements/loop.md), variables hold what changes between iterations. They are defined before the loop, and a variables element at the end of `do` replaces them with the values for the next iteration. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { GuestForm } from "./components/guest-form"; type Schema = { render: React.ReactNode; struct: [ s.Variables<{ i: number; guests: string[] }>, s.Loop< [s.Form<{ guest: string }>, s.Variables<{ i: number; guests: string[] }>] >, s.Return<{ guests: string[] }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { variables: () => ({ i: 0, guests: [] }), }, { loop: { while: ({ i }) => i < 3, do: [ { form: { fields: ({ i }) => ({ guest: ["", [i]] }), render: ({ fields, values, back, next }) => ( ), }, }, { variables: ({ i, guests, guest }) => ({ i: i + 1, guests: [...guests, guest], }), }, ], }, }, { return: ({ guests }) => ({ guests }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // guests: string[]; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` Return new values instead of mutating the existing ones, as in `[...guests, guest]`, so that navigating back restores the values of the previous iteration. # Condition Source: https://formity.app/docs/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; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ working: ["yes", []] }), render: ({ fields, next }) => , }, }, { variables: () => ({ company: null }), }, { condition: { if: ({ working }) => working === "yes", then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, { form: { fields: () => ({ study: ["business", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ working, company, study }) => ({ working, company, study }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // working: string; // company: string | null; // study: string; // } console.log(output); }, []); return 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`. # Switch Source: https://formity.app/docs/flow-elements/switch > Learn how the switch element branches the flow into multiple cases. ## Usage The **switch** element branches the flow based on multiple cases. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { InterestedForm } from "./components/interested-form"; import { WhyYesForm } from "./components/why-yes-form"; import { WhyNotForm } from "./components/why-not-form"; import { WhyNotSureForm } from "./components/why-not-sure-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ interested: string }>, s.Switch<{ branches: [ [ s.Form<{ whyYes: string }>, s.Return<{ interested: "yes"; whyYes: string }>, ], [ s.Form<{ whyNot: string }>, s.Return<{ interested: "no"; whyNot: string }>, ], ]; default: [ s.Form<{ whyNotSure: string }>, s.Return<{ interested: "notSure"; whyNotSure: string }>, ]; }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ interested: ["yes", []] }), render: ({ fields, next }) => ( ), }, }, { switch: { branches: [ { case: ({ interested }) => interested === "yes", then: [ { form: { fields: () => ({ whyYes: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ whyYes }) => ({ interested: "yes", whyYes }), }, ], }, { case: ({ interested }) => interested === "no", then: [ { form: { fields: () => ({ whyNot: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ whyNot }) => ({ interested: "no", whyNot }), }, ], }, ], default: [ { form: { fields: () => ({ whyNotSure: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ whyNotSure }) => ({ interested: "notSure", whyNotSure }), }, ], }, }, ]; export default function App() { const onReturn = useCallback>((output) => { // | { // interested: "yes"; // whyYes: string; // } // | { // interested: "no"; // whyNot: string; // } // | { // interested: "notSure"; // whyNotSure: string; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` Each `case` function receives the flow values and returns a boolean. The `then` of the first case that returns `true` is executed, or `default` if none does. In the `Schema`, each switch element has an `s.Switch` entry in `struct`, with the entries of the elements of each branch in `branches`, in the same order, and the ones of `default`. # Jump Source: https://formity.app/docs/flow-elements/jump > Learn how the jump element defines a form that can be jumped to from anywhere in the flow. ## Usage The **jump** element defines a form that can be jumped to from anywhere in the flow. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { TopicsForm } from "./components/topics-form"; import { FrequencyForm } from "./components/frequency-form"; import { EmailForm } from "./components/email-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ topics: string }>, s.Form<{ frequency: string }>, s.Jump>, s.Return<{ topics: string; frequency: string; email: string; }>, ]; inputs: { topics: string; frequency: string; }; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ topics: ["all", []] }), render: ({ fields, next, jump }) => ( ), }, }, { form: { fields: () => ({ frequency: ["weekly", []] }), render: ({ fields, back, next }) => ( ), }, }, { jump: { id: "email", at: { form: { fields: () => ({ email: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, }, }, { return: ({ topics, frequency, email }) => ({ topics, frequency, email, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // topics: string; // frequency: string; // email: string; // } console.log(output); }, []); return ( flow={flow} inputs={{ topics: "all", frequency: "weekly" }} onReturn={onReturn} /> ); } ``` The `id` identifies the jump element and `at` contains the [form](https://formity.app/docs/flow-elements/form.md) to jump to. The form is still a regular step, so `next` reaches it too. In the `Schema`, each jump element has an `s.Jump` entry in `struct`, which wraps the `s.Form` entry of the form defined in `at`. ## Jumping to a form The `render` function of every [form](https://formity.app/docs/flow-elements/form.md) receives a `jump` function. It receives the `id` of a jump element and the form values, and goes to the form of that jump element. ```tsx // src/components/topics-form.tsx import { useState } from "react"; import type { Next, Jump } from "@formity/react"; type Values = { topics: string }; type TopicsFormProps = { fields: Values; next: Next; jump: Jump; }; export function TopicsForm({ fields, next, jump }: TopicsFormProps) { const [topics, setTopics] = useState(fields.topics); return (
{ event.preventDefault(); next({ topics }); }} >
); } ``` There are a few things to keep in mind: - The jump element can be anywhere in the flow, before or after the current step. - If no jump element has that `id`, nothing happens and the current step stays. - Calling `back` from the form that was jumped to returns to the step the jump was made from, unless [`history`](https://formity.app/docs/basic-concepts/history.md) is `false`. - A jump element can be reached from anywhere, so previous elements may not have been visited and their values may be missing. Provide default values with [`inputs`](https://formity.app/docs/basic-concepts/inputs.md), which always exist. # Loop Source: https://formity.app/docs/flow-elements/loop > Learn how the loop element repeats elements of the flow while a condition is true. ## Usage The **loop** element repeats a set of flow elements while a condition is `true`. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { QuestionForm } from "./components/question-form"; type Schema = { render: React.ReactNode; struct: [ s.Variables<{ i: number; questions: { question: string; options: { value: string; label: string }[]; default: string; correct: string; }[]; right: number; wrong: number; }>, s.Loop< [ s.Variables<{ question: { question: string; options: { value: string; label: string }[]; default: string; correct: string; }; }>, s.Form<{ answer: string }>, s.Variables<{ i: number; right: number; wrong: number }>, ] >, s.Return<{ right: number; wrong: number }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { variables: () => ({ i: 0, questions: [ { question: "What is the capital of Australia?", options: [ { value: "sydney", label: "Sydney" }, { value: "melbourne", label: "Melbourne" }, { value: "canberra", label: "Canberra" }, ], default: "sydney", correct: "canberra", }, { question: "Who painted 'The Starry Night'?", options: [ { value: "picasso", label: "Pablo Picasso" }, { value: "vangogh", label: "Vincent van Gogh" }, { value: "dali", label: "Salvador Dalí" }, ], default: "picasso", correct: "vangogh", }, ], right: 0, wrong: 0, }), }, { loop: { while: ({ i, questions }) => i < questions.length, do: [ { variables: ({ i, questions }) => ({ question: questions[i], }), }, { form: { fields: ({ question, i }) => ({ answer: [question.default, [i]], }), render: ({ fields, values, back, next }) => ( ), }, }, { variables: ({ i, question, answer, right, wrong }) => ({ i: i + 1, right: question.correct === answer ? right + 1 : right, wrong: question.correct === answer ? wrong : wrong + 1, }), }, ], }, }, { return: ({ right, wrong }) => ({ right, wrong }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // right: number; // wrong: number; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The `while` function receives the flow values and returns a boolean. The elements in `do` are executed while it is `true`, and the flow continues after the loop when it is `false`. In the `Schema`, each loop element has an `s.Loop` entry in `struct`, with the entries of the elements of `do`, in the same order as they appear in the flow. > A form inside a loop is the same form element in every iteration, so two things have to change between iterations. The rendered component needs a `key` that changes, like `key={values.i}`, so that React mounts a new form instead of reusing the previous one. The array of each field also needs a value that changes, like `[i]`, so that the field starts from its default value instead of keeping the previous answer. # Yield Source: https://formity.app/docs/flow-elements/yield > Learn how the yield element passes values to the `onYield` callback. ## Usage The **yield** element yields values while the multi-step form is in progress. When the flow passes through it, the `onYield` callback is called with those values and the flow continues. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnYield, type OnReturn, } from "@formity/react"; import { SeatForm } from "./components/seat-form"; import { EmailForm } from "./components/email-form"; type Schema = { render: React.ReactNode; struct: [ s.Form<{ seat: string }>, s.Yield<{ next: [{ type: "hold"; seat: string }]; back: [{ type: "release"; seat: string }]; }>, s.Form<{ email: string }>, s.Return<{ seat: string; email: string }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { form: { fields: () => ({ seat: ["", []] }), render: ({ fields, next }) => , }, }, { yield: { next: ({ seat }) => [{ type: "hold", seat }], back: ({ seat }) => [{ type: "release", seat }], }, }, { form: { fields: () => ({ email: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, { return: ({ seat, email }) => ({ seat, email }), }, ]; export default function App() { const onYield = useCallback>((output) => { // | { // type: "hold"; // seat: string; // } // | { // type: "release"; // seat: string; // } console.log(output); }, []); const onReturn = useCallback>((output) => { // { // seat: string; // email: string; // } console.log(output); }, []); return flow={flow} onYield={onYield} onReturn={onReturn} />; } ``` The `next` function is called when the flow passes through the yield element going forward. It receives the flow values and returns an array, and `onYield` is called once for each of its elements. The `back` function is called when the flow passes through the yield element going backward. It receives the flow values and returns an array, and `onYield` is called once for each of its elements. In the `Schema`, each yield element has an `s.Yield` entry in `struct`. Its `next` and `back` types must match the arrays returned by the `next` and `back` functions. The `OnYield` type is the type of the `onYield` callback, and `YieldOutput` is the type of the values it receives, which is the union of the values of all the yield elements. # Module Source: https://formity.app/docs/flow-elements/module > Learn how the module element includes a nested flow that can be defined outside the main flow. ## Usage The **module** element includes a nested flow that can be defined outside the main flow. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import { ContactForm } from "./components/contact-form"; import { CompanyForm } from "./components/company-form"; type Schema = { render: React.ReactNode; struct: [ s.Module<{ render: React.ReactNode; struct: [s.Form<{ name: string; type: string }>]; inputs: Record; values: Record; params: Record; }>, s.Module<{ render: React.ReactNode; struct: [ s.Variables<{ company: string | null }>, s.Condition<{ then: [s.Form<{ company: string }>]; else: []; }>, ]; inputs: Record; values: { type: string }; params: Record; }>, s.Return<{ name: string; type: string; company: string | null; }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { module: [ { form: { fields: () => ({ name: ["", []], type: ["company", []] }), render: ({ fields, next }) => ( ), }, }, ], }, { module: [ { variables: () => ({ company: null }), }, { condition: { if: ({ type }) => type === "company", then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, ], }, { return: ({ name, type, company }) => ({ name, type, company, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { // { // name: string; // type: string; // company: string | null; // } console.log(output); }, []); return flow={flow} onReturn={onReturn} />; } ``` The `module` property is an array of flow elements, which are executed in order as if they were placed directly in the flow. It accepts any flow elements, including other modules. In the `Schema`, each module element has an `s.Module` entry in `struct`, which contains the schema of the module with the entries of its own elements. ## Module schema The schema of a module has the same properties as the schema of a flow, plus `values`: - `render`: The type returned by the `render` function of the forms in the module. - `struct`: The entries of the elements of the module, in the same order. - `inputs`: The [`inputs`](https://formity.app/docs/basic-concepts/inputs.md) that the module uses. - `values`: The flow values that the module uses from the elements before it. - `params`: The [`params`](https://formity.app/docs/basic-concepts/params.md) that the module uses. It must be compatible with the flow that contains it: - `render` must match the flow's `render`. - `inputs` must be a subset of the flow's `inputs`. - `values` must be a subset of the flow values at the point where the module is placed. - `params` must be a subset of the flow's `params`. The values collected inside a module are added to the flow values, so the elements after the module can use them as if they had been collected in the flow itself. ## Separate files Modules are most useful when defined in separate files, which keeps the flow clean and allows reuse. Each file exports the schema of the module and its elements, typed with `Module`. `src/modules/contact.tsx`: ```tsx // src/modules/contact.tsx import type { Module, s } from "@formity/react"; import { ContactForm } from "../components/contact-form"; export type Schema = { render: React.ReactNode; struct: [s.Form<{ name: string; type: string }>]; inputs: Record; values: Record; params: Record; }; export const subFlow: Module = [ { form: { fields: () => ({ name: ["", []], type: ["company", []] }), render: ({ fields, next }) => , }, }, ]; ``` `src/modules/company.tsx`: ```tsx // src/modules/company.tsx import type { Module, s } from "@formity/react"; import { CompanyForm } from "../components/company-form"; export type Schema = { render: React.ReactNode; struct: [ s.Variables<{ company: string | null }>, s.Condition<{ then: [s.Form<{ company: string }>]; else: []; }>, ]; inputs: Record; values: { type: string }; params: Record; }; export const subFlow: Module = [ { variables: () => ({ company: null }), }, { condition: { if: ({ type }) => type === "company", then: [ { form: { fields: () => ({ company: ["", []] }), render: ({ fields, back, next }) => ( ), }, }, ], else: [], }, }, ]; ``` Finally, the flow imports both modules. The schema of each module is passed to its `s.Module` entry, and its elements are passed to the `module` property. ```tsx // src/app.tsx import { useCallback } from "react"; import { Formity, type s, type Flow, type OnReturn } from "@formity/react"; import * as contact from "./modules/contact"; import * as company from "./modules/company"; type Schema = { render: React.ReactNode; struct: [ s.Module, s.Module, s.Return<{ name: string; type: string; company: string | null; }>, ]; inputs: Record; params: Record; }; const flow: Flow = [ { module: contact.subFlow }, { module: company.subFlow }, { return: ({ name, type, company }) => ({ name, type, company, }), }, ]; export default function App() { const onReturn = useCallback>((output) => { console.log(output); // { // name: string; // type: string; // company: string | null; // } }, []); return flow={flow} onReturn={onReturn} />; } ``` For a complete example, see the [Using modules](https://formity.app/docs/guides/using-modules.md) guide. # Animating forms Source: https://formity.app/docs/guides/animating-forms > Learn how to add animations to a multi-step form using Motion. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## Initial steps We'll show you how to add animations to a multi-step form using [Motion](https://motion.dev/). A pre-built form is available in the GitHub repository below, so go ahead and clone it to follow along. ```bash git clone https://github.com/martiserra99/formity-react-hook-form ``` Then install the dependencies. ```bash npm install ``` Finally, install Motion. ```bash npm install motion ``` 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](https://formity.app/docs/use-with-form-libraries/react-hook-form.md) 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 three files that we'll update, and the rest of the repo stays as it is. The first one is `src/types/status.ts`, with the status of the form. ```tsx // src/types/status.ts export type Status = FormStatus | DoneStatus; export type FormStatus = { type: "form"; submitting: boolean; }; export type DoneStatus = { type: "done"; output: T; }; ``` The status is `FormStatus` while the form is shown, with `submitting` as `true` while being submitted. After that it's a `DoneStatus`, with the values that were submitted in `output`. The second 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> { defaultValues: DefaultValues; resolver: Resolver; heading: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; status: FormStatus; } export function Form>({ defaultValues, resolver, heading, content, buttons, back, next, status, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{content.map((field, index) => ( ))}
{buttons.back && ( )}
); } ``` Each field in `content` is described by an `Item` object and rendered by the `ItemView` component. The form also receives the status, using the `FormStatus` type mentioned before. The third 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => (
), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` With this code there's nothing to animate yet. When `next` or `back` is called, `Formity` renders the new step and React replaces one `Form` with the other instantly, since they have different keys. ## Animations We'll animate the transition between steps. One step slides out and the other slides in, in a direction that depends on whether the user navigates to the next step or the previous one. So we need to track whether the user is navigating and in which direction. We'll add a `move` property to the `FormStatus` type, which is `"next"` or `"back"` while navigating and `false` otherwise. ```diff // src/types/status.ts @@ -2,6 +2,7 @@ export type FormStatus = { type: "form"; + move: "next" | "back" | false; submitting: boolean; }; ``` Then, we'll update the `Form` component. What it rendered until now is moved to a `View` component, and `Form` becomes a wrapper that animates it using `AnimatePresence` and a `motion.div`. It also receives two new props. The `id` prop identifies the step, and the `setStatus` prop lets it update the status when the user navigates. ```diff // src/components/form/index.tsx @@ -1,7 +1,17 @@ import type { DefaultValues, Resolver } from "react-hook-form"; import type { Back, Next } from "@formity/react"; +import type { MotionProps } from "motion/react"; +import { + useMemo, + useState, + useEffect, + useCallback, + useEffectEvent, +} from "react"; + import { useForm, FormProvider } from "react-hook-form"; +import { AnimatePresence, motion } from "motion/react"; import type { FormStatus } from "@/types/status"; @@ -9,6 +19,7 @@ import { Button } from "../button"; interface FormProps> { + id: string; defaultValues: DefaultValues; resolver: Resolver; heading: string; @@ -20,9 +31,90 @@ back: Back; next: Next; status: FormStatus; + setStatus: (status: FormStatus) => void; } export function Form>({ + id, + back, + next, + status, + setStatus, + ...rest +}: FormProps) { + const [fields, setFields] = useState(); + + const move = useEffectEvent((move: FormStatus["move"]) => { + if (move === "next") return next(fields); + if (move === "back") return back(fields); + }); + + useEffect(() => move(status.move), [status.move]); + + const handleNext = useCallback>( + (fields) => { + setStatus({ type: "form", move: "next", submitting: false }); + setFields(fields); + }, + [setStatus, setFields], + ); + + const handleBack = useCallback>( + (fields) => { + setStatus({ type: "form", move: "back", submitting: false }); + setFields(fields); + }, + [setStatus, setFields], + ); + + const animate = useMemo( + () => ({ x: 0, opacity: 1, transition: { delay: 0.25, duration: 0.25 } }), + [], + ); + + return ( + + { + if (definition === animate) { + setStatus({ type: "form", move: false, submitting: false }); + } + }} + {...motionProps(status.move)} + className="h-full" + > + + + + ); +} + +function motionProps(move: FormStatus["move"]): MotionProps { + if (move === "next") { + return { + initial: { x: 50, opacity: 0 }, + exit: { x: -50, opacity: 0, transition: { delay: 0, duration: 0.25 } }, + }; + } + if (move === "back") { + return { + initial: { x: -50, opacity: 0 }, + exit: { x: 50, opacity: 0, transition: { delay: 0, duration: 0.25 } }, + }; + } + return {}; +} + +function View>({ defaultValues, resolver, heading, @@ -31,7 +123,7 @@ back, next, status, -}: FormProps) { +}: Omit, "id" | "setStatus">) { const form = useForm({ defaultValues, resolver }); return ( ; params: { status: FormStatus; + setStatus: (status: FormStatus) => void; }; }; @@ -60,7 +61,7 @@ }), render: ({ fields, params, back, next }) => ( ), }, @@ -113,7 +115,7 @@ }), render: ({ fields, params, back, next }) => ( ), }, @@ -155,7 +158,7 @@ }), render: ({ fields, params, back, next }) => ( ), }, @@ -205,7 +209,7 @@ }), render: ({ fields, params, back, next }) => ( ), }, @@ -254,11 +259,12 @@ export default function App() { const [status, setStatus] = useState>>({ type: "form", + move: false, submitting: false, }); const onReturn = useCallback>(async (output) => { - setStatus({ type: "form", submitting: true }); + setStatus({ type: "form", move: false, submitting: true }); // Show output in the console console.log(output); @@ -273,12 +279,18 @@ return ( setStatus({ type: "form", submitting: false })} + onStartOver={() => + setStatus({ type: "form", move: false, submitting: false }) + } /> ); } return ( - flow={flow} params={{ status }} onReturn={onReturn} /> + + flow={flow} + params={{ status, setStatus }} + onReturn={onReturn} + /> ); } ``` ## Progress bar Let's add a progress bar at the top of the form. Unlike the steps, it shouldn't slide in and out, so it can't be part of `Form`. It has to be rendered next to it, knowing which step is being shown. This is where the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook comes in. It lets us render anything we want in each step and not just a `ReactNode`, so each step will render both the form and its progress. The hook is called in a new `Steps` component that replaces `Formity` in `App`. It takes the form and the progress of the current step, and renders the progress bar above the form. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { useFormity, type s, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import { motion } from "motion/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: { progress: { numberSteps: number; currentStep: number; }; form: 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; params: { status: FormStatus; setStatus: (status: FormStatus) => void; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ({ progress: { numberSteps: 3, currentStep: 1, }, form: ( ), }), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ({ progress: { numberSteps: 3, currentStep: 2, }, form: ( ), }), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ({ progress: { numberSteps: 3, currentStep: 3, }, form: ( ), }), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ({ progress: { numberSteps: 3, currentStep: 3, }, form: ( ), }), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", move: false, submitting: false, }); const onReturn = useCallback>(async (output) => { setStatus({ type: "form", move: false, 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 ( setStatus({ type: "form", move: false, submitting: false }) } /> ); } return ; } interface StepsProps { params: Schema["params"]; onReturn: OnReturn; } function Steps({ params, onReturn }: StepsProps) { const { progress, form } = useFormity({ flow, params, onReturn }); return (
{form}
); } ``` The progress bar is a `motion.div` scaled to `currentStep / numberSteps`, so Motion animates it when the step changes. As with the form, `initial={false}` skips the animation on load. # Conditional fields Source: https://formity.app/docs/guides/conditional-fields > Learn how to add fields that appear when a condition is met. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## 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. ```bash git clone https://github.com/martiserra99/formity-react-hook-form ``` Then install the dependencies. ```bash 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](https://formity.app/docs/use-with-form-libraries/react-hook-form.md) 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 ; } case "input": { return ; } case "number": { return ; } case "select": { return ; } case "textarea": { return ; } case "multi-select": { return ; } } } ``` 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 (
{columns.map((item, i) => ( ))}
); } ``` 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> { defaultValues: DefaultValues; resolver: Resolver; heading: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; status: FormStatus; } export function Form>({ defaultValues, resolver, heading, content, buttons, back, next, status, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{content.map((field, index) => ( ))}
{buttons.back && ( )}
); } ``` 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => (
), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( 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](https://formity.app/docs/flow-elements/condition.md) 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> { type: "condition"; if: (values: T) => boolean; then: Item[]; else: Item[]; } export function ConditionView>( item: Condition, ) { const values = useWatch() as T; const items = item.if(values) ? item.then : item.else; return ( <> {items.map((item, i) => ( ))} ); } ``` 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> { type: "switch"; branches: { case: (values: T) => boolean; then: Item[]; }[]; default: Item[]; } export function SwitchView>(item: Switch) { 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) => ( ))} ); } ``` 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`: ```diff // src/components/form/item/index.tsx @@ -1,3 +1,5 @@ +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"; @@ -5,10 +7,24 @@ import { TextareaView, type Textarea } from "./textarea"; import { MultiSelectView, type MultiSelect } from "./multi-select"; -export type Item = Columns | Input | Number | Select | Textarea | MultiSelect; +export type Item> = + | Condition + | Switch + | Columns + | Input + | Number + | Select + | Textarea + | MultiSelect; -export function ItemView(item: Item) { +export function ItemView>(item: Item) { switch (item.type) { + case "condition": { + return ; + } + case "switch": { + return ; + } case "columns": { return ; } ``` The `columns` item contains other items, so it has to be generic as well. `src/components/form/item/columns.tsx`: ```diff // src/components/form/item/columns.tsx @@ -1,11 +1,13 @@ import { ItemView, type Item } from "."; -export interface Columns { +export interface Columns> { type: "columns"; - columns: Item[]; + columns: Item[]; } -export function ColumnsView({ columns }: Columns) { +export function ColumnsView>({ + columns, +}: Columns) { return (
{columns.map((item, i) => ( ``` Finally, in `Form` the `content` prop changes from `Item[]` to `Item[]`. `src/components/form/index.tsx`: ```diff // src/components/form/index.tsx @@ -12,7 +12,7 @@ defaultValues: DefaultValues; resolver: Resolver; heading: string; - content: Item[]; + content: Item[]; buttons: { back: string | null; next: string; ``` ## 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](https://formity.app/docs/flow-elements/variables.md) 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, ]; inputs: Record; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ working: ["no", []], company: ["", []], }), render: ({ fields, params, back, next }) => ( 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>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( 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, ]; inputs: Record; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ projectType: ["website", []], websiteName: ["", []], appName: ["", []], projectName: ["", []], }), render: ({ fields, params, back, next }) => ( 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>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` # Review step Source: https://formity.app/docs/guides/review-step > Learn how to add a review step that lets users edit any previous answer before submitting. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## 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. ```bash git clone https://github.com/martiserra99/formity-review-step ``` Then install the dependencies. ```bash 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> { defaultValues: DefaultValues; resolver: Resolver; heading: string; message: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; } export function Form>({ defaultValues, resolver, heading, message, content, buttons, back, next, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{message}

{content.map((item, i) => ( ))}
{buttons.back && ( )}
); } ``` 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>; status: FormStatus; } export function Review({ heading, message, content, button, next, status, }: ReviewProps) { return (

{heading}

{message}

{content.map((item, i) => ( {}} /> ))}
); } ``` 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; 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, s.Form, s.Form, s.Form, s.Form>, s.Return, ]; inputs: Record; params: { status: FormStatus; }; }; export const flow: Flow = [ { form: { fields: () => ({ name: ["", []], email: ["", []], }), render: ({ fields, back, next }) => (
), }, }, { form: { fields: () => ({ experience: ["", []], jobTitle: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, { form: { fields: () => ({ employmentType: ["", []], workArrangement: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, { form: { fields: () => ({ whyRole: ["", []], greatestStrength: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, { form: { fields: () => ({}), render: ({ values, params, next }) => ( ), }, }, { 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>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ; } ``` 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](https://formity.app/docs/flow-elements/jump.md) 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; 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.Jump>, s.Jump>, s.Jump>, s.Jump>>, s.Return, ]; inputs: Record; params: { status: FormStatus; }; }; export const flow: Flow = [ { jump: { id: "personal", at: { form: { fields: () => ({ name: ["", []], email: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, }, }, { jump: { id: "background", at: { form: { fields: () => ({ experience: ["", []], jobTitle: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, }, }, { jump: { id: "preferences", at: { form: { fields: () => ({ employmentType: ["", []], workArrangement: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, }, }, { jump: { id: "about", at: { form: { fields: () => ({ whyRole: ["", []], greatestStrength: ["", []], }), render: ({ fields, back, next }) => ( ), }, }, }, }, { jump: { id: "review", at: { form: { fields: () => ({}), render: ({ values, params, next }) => ( ), }, }, }, }, { 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`](https://formity.app/docs/basic-concepts/inputs.md), which always exist. We type them as `Values` in the `Schema` and export an `inputs` object with a default value for each field. ```diff // src/flow.tsx @@ -42,7 +42,7 @@ s.Jump>>, s.Return, ]; - inputs: Record; + inputs: Values; params: { status: FormStatus; }; @@ -341,3 +341,14 @@ }), }, ]; + +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. ```diff // src/app.tsx @@ -6,7 +6,7 @@ import { Done } from "./components/done"; -import { flow, type Schema } from "./flow"; +import { flow, inputs, type Schema } from "./flow"; export default function App() { const [status, setStatus] = useState>>({ @@ -35,5 +35,12 @@ ); } - return ; + return ( + + ); } ``` ## Navigation with jumps 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. ```diff // src/components/form/index.tsx @@ -1,5 +1,5 @@ import type { DefaultValues, Resolver } from "react-hook-form"; -import type { Back, Next } from "@formity/react"; +import type { Next, Jump } from "@formity/react"; import { useForm, FormProvider } from "react-hook-form"; @@ -16,8 +16,9 @@ back: string | null; next: string; }; - back: Back; next: Next; + jump: Jump; + prev: string | null; } export function Form>({ @@ -27,8 +28,9 @@ message, content, buttons, - back, next, + jump, + prev, }: FormProps) { const form = useForm({ defaultValues, resolver }); return ( @@ -52,7 +54,7 @@ ``` 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. ```diff // src/components/review/index.tsx @@ -1,4 +1,4 @@ -import type { Next } from "@formity/react"; +import type { Next, Jump } from "@formity/react"; import type { FormStatus } from "../../types/status"; import { ItemView, type Item } from "./item"; @@ -10,6 +10,7 @@ content: Item[]; button: string; next: Next>; + jump: Jump>; status: FormStatus; } @@ -19,6 +20,7 @@ content, button, next, + jump, status, }: ReviewProps) { return ( @@ -30,7 +32,7 @@
{content.map((item, i) => ( - {}} /> + jump(edit, {})} /> ))}
``` 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. ```diff // src/flow.tsx @@ -58,7 +58,7 @@ name: ["", []], email: ["", []], }), - render: ({ fields, back, next }) => ( + render: ({ fields, next, jump }) => ( ), }, @@ -105,7 +106,7 @@ experience: ["", []], jobTitle: ["", []], }), - render: ({ fields, back, next }) => ( + render: ({ fields, next, jump }) => ( ), }, @@ -157,7 +159,7 @@ employmentType: ["", []], workArrangement: ["", []], }), - render: ({ fields, back, next }) => ( + render: ({ fields, next, jump }) => ( ), }, @@ -210,7 +213,7 @@ whyRole: ["", []], greatestStrength: ["", []], }), - render: ({ fields, back, next }) => ( + render: ({ fields, next, jump }) => ( ), }, @@ -259,7 +263,7 @@ at: { form: { fields: () => ({}), - render: ({ values, params, next }) => ( + render: ({ values, params, next, jump }) => ( ), ``` ## 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`](https://formity.app/docs/basic-concepts/history.md) prop to `false` disables it. ```diff // src/app.tsx @@ -40,6 +40,7 @@ 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`. ```diff // src/components/form/index.tsx @@ -15,10 +15,12 @@ buttons: { back: string | null; next: string; + edit: string; }; next: Next; jump: Jump; prev: string | null; + edit: boolean; } export function Form>({ @@ -31,12 +33,20 @@ next, jump, prev, + edit, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (
- + { + if (edit) jump("review", fields); + else next(fields); + })} + >

@@ -50,7 +60,7 @@ ))}

- {buttons.back && ( + {buttons.back && !edit && (
``` The `flow` gets an `edit` value that starts as `false` in `inputs`. A [variables](https://formity.app/docs/flow-elements/variables.md) 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; 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.Jump>, s.Jump>, s.Jump>, s.Variables<{ edit: boolean }>, s.Jump>>, s.Return, ]; inputs: Values & { edit: boolean }; params: { status: FormStatus; }; }; export const flow: Flow = [ { jump: { id: "personal", at: { form: { fields: () => ({ name: ["", []], email: ["", []], }), render: ({ fields, values, next, jump }) => ( ), }, }, }, }, { jump: { id: "background", at: { form: { fields: () => ({ experience: ["", []], jobTitle: ["", []], }), render: ({ fields, values, next, jump }) => ( ), }, }, }, }, { jump: { id: "preferences", at: { form: { fields: () => ({ employmentType: ["", []], workArrangement: ["", []], }), render: ({ fields, values, next, jump }) => ( ), }, }, }, }, { jump: { id: "about", at: { form: { fields: () => ({ whyRole: ["", []], greatestStrength: ["", []], }), render: ({ fields, values, next, jump }) => ( ), }, }, }, }, { variables: () => ({ edit: true, }), }, { jump: { id: "review", at: { form: { fields: () => ({}), render: ({ values, params, next, jump }) => ( ), }, }, }, }, { 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, }; ``` # State outside the form Source: https://formity.app/docs/guides/state-outside-the-form > Learn how to keep the form values outside the form to show a live summary. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## Initial steps We'll show you how to keep the form values outside the form, so they're always available as users type. To follow along, start by cloning the repository below, which is our starting point. ```bash git clone https://github.com/martiserra99/formity-state-outside-the-form ``` Then install the dependencies. ```bash npm install ``` The repo is a React project using Vite and TypeScript, with `@formity/react` already installed for you. It contains a four-step checkout form built with React Hook Form, and a summary panel. ## Before we start Before changing anything, let's look at the code we start from. There are three 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 type { FormStatus } from "@/types/status"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; interface FormProps> { defaultValues: DefaultValues; resolver: Resolver; heading: string; message: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; status: FormStatus; } export function Form>({ defaultValues, resolver, heading, message, content, buttons, back, next, status, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{message}

{content.map((item, i) => ( ))}
{buttons.back && ( )}
); } ``` 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/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 * as constants from "./constants"; type Values = UnionToIntersection; type Fields = { contact: { firstName: string; lastName: string; email: string; }; shipping: { address: string; city: string; postalCode: string; country: string; }; delivery: { deliveryMethod: string; }; payment: { cardholderName: string; cardNumber: string; expiryDate: string; }; }; export type Schema = { render: React.ReactNode; struct: [ s.Form, s.Form, s.Form, s.Form, s.Return, ]; inputs: Record; params: { status: FormStatus; }; }; export const flow: Flow = [ { form: { fields: () => ({ firstName: ["", []], lastName: ["", []], email: ["", []], }), render: ({ fields, params, back, next }) => (
), }, }, { form: { fields: () => ({ address: ["", []], city: ["", []], postalCode: ["", []], country: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { form: { fields: () => ({ deliveryMethod: ["", []], }), render: ({ fields, params, back, next }) => ( ({ value: m.value, label: m.label, description: m.description, priceLabel: m.priceLabel, })), }, ]} buttons={{ back: "Back", next: "Continue" }} back={back} next={next} status={params.status} /> ), }, }, { form: { fields: () => ({ cardholderName: ["", []], cardNumber: ["", []], expiryDate: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: (values) => values, }, ]; ``` The `Values` type combines the fields of the four steps into a single object. It takes the union of the step types with `Fields[keyof Fields]`, and merges them with `UnionToIntersection`. The third one is `src/app.tsx`, which renders the form next to the summary. ```tsx // src/app.tsx import type { OnReturn, ReturnOutput } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import { useState, useCallback } from "react"; import { useFormity } from "@formity/react"; import { Summary } from "./components/summary"; import { Done } from "./components/done"; import { flow, type Schema } from "./flow"; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ; } interface FormProps { status: FormStatus; onReturn: OnReturn; } function Form({ status, onReturn }: FormProps) { const form = useFormity({ flow, params: { status }, onReturn, }); return (
{form}
); } ``` For now the `Summary` component receives empty strings, so it doesn't show any of the form values. We can't pass them yet, since the values of a step stay inside its `Form` until it's submitted. ## Watching changes The summary must update as users type, but Formity only receives a step's values when it's submitted. So we'll keep the values in a state of the parent, updated on every change. We need to update the `Form` component, since it knows when a field changes. It receives the values of all the steps in `values`, and on every change it calls `onValuesChange` with them updated. We also add a type parameter to type the new props. `T` is the type of the fields of the step, and `U` is the type of the values of all the steps, which include those fields. ```diff // src/components/form/index.tsx @@ -2,13 +2,14 @@ import type { Back, Next } from "@formity/react"; import { useForm, FormProvider } from "react-hook-form"; +import { useEffect, useEffectEvent } from "react"; import type { FormStatus } from "@/types/status"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; -interface FormProps> { +interface FormProps, U extends T> { defaultValues: DefaultValues; resolver: Resolver; heading: string; @@ -21,9 +22,11 @@ back: Back; next: Next; status: FormStatus; + values: U; + onValuesChange: (values: U) => void; } -export function Form>({ +export function Form, U extends T>({ defaultValues, resolver, heading, @@ -33,8 +36,22 @@ back, next, status, -}: FormProps) { + values, + onValuesChange, +}: FormProps) { const form = useForm({ defaultValues, resolver }); + + const onFieldsChange = useEffectEvent(({ values: fields }: { values: T }) => { + onValuesChange({ ...values, ...fields }); + }); + + useEffect(() => { + return form.subscribe({ + formState: { values: true }, + callback: onFieldsChange, + }); + }, [form]); + return ( ``` React Hook Form's `subscribe` function calls `onFieldsChange` whenever a field of the step changes. The same idea fits any form library, as long as it lets you listen to field changes. We define this function with `useEffectEvent`, from React 19.2, so that it accesses the latest `values`. It only receives the current step's fields, so it merges them into `values` and calls `onValuesChange`. ## Updating the flow Each `Form` is rendered inside the `flow`, so the two extra props have to reach it through [`params`](https://formity.app/docs/basic-concepts/params.md). We also export `initialValues`, with an initial value for every field, to use as the parent's initial state. ```diff // src/flow.tsx @@ -45,6 +45,8 @@ inputs: Record; params: { status: FormStatus; + values: Values; + onValuesChange: (values: Values) => void; }; }; @@ -99,6 +101,8 @@ back={back} next={next} status={params.status} + values={params.values} + onValuesChange={params.onValuesChange} /> ), }, @@ -161,6 +165,8 @@ back={back} next={next} status={params.status} + values={params.values} + onValuesChange={params.onValuesChange} /> ), }, @@ -199,6 +205,8 @@ back={back} next={next} status={params.status} + values={params.values} + onValuesChange={params.onValuesChange} /> ), }, @@ -247,6 +255,8 @@ back={back} next={next} status={params.status} + values={params.values} + onValuesChange={params.onValuesChange} /> ), }, @@ -255,3 +265,17 @@ return: (values) => values, }, ]; + +export const initialValues: Values = { + email: "", + firstName: "", + lastName: "", + address: "", + city: "", + postalCode: "", + country: "", + deliveryMethod: "", + cardholderName: "", + cardNumber: "", + expiryDate: "", +}; ``` ## Using the state Finally, we create the state with `useState`, starting from `initialValues`. It lives in the component that calls the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook, which is also the one that renders the summary. The hook receives `values` and `setValues` through `params`, the second one as `onValuesChange`. Each `Form` calls it on every change, which keeps the state up to date. All that remains is to use the state where we need it. The `Summary` component receives its values instead of the empty ones, and shows a summary that updates as users type. ```tsx // src/app.tsx import type { OnReturn, ReturnOutput } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import { useState, useCallback } from "react"; import { useFormity } from "@formity/react"; import { Summary } from "./components/summary"; import { Done } from "./components/done"; import { flow, initialValues, type Schema } from "./flow"; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ; } interface FormProps { status: FormStatus; onReturn: OnReturn; } function Form({ status, onReturn }: FormProps) { const [values, setValues] = useState(initialValues); const form = useFormity({ flow, params: { status, values, onValuesChange: setValues }, onReturn, }); return (
{form}
); } ``` # Sidebar navigation Source: https://formity.app/docs/guides/sidebar-navigation > Learn how to add a sidebar that lets users jump back to any previously completed step. Note: some code blocks are diffs against the previous version of the same file, which is named in the first line of the block. ## Initial steps We'll show you how to make a sidebar track the user's progress and jump to any step that's completed. To follow along, start by cloning the repository below, which is our starting point. ```bash git clone https://github.com/martiserra99/formity-sidebar-navigation ``` Then install the dependencies. ```bash npm install ``` The repo is a React project using Vite and TypeScript, with `@formity/react` already installed for you. It contains an onboarding form built with React Hook Form, with a review step and a sidebar. ## 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 } from "react-hook-form"; import type { Next, Jump } from "@formity/react"; import type { z } from "zod"; import { useForm, FormProvider } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; interface FormProps> { defaultValues: DefaultValues; validate: z.ZodType; heading: string; message: string; content: Item[]; buttons: { next: string; back: string | null; }; next: Next; jump: Jump; prev: string | null; } export function Form>({ defaultValues, validate, heading, message, content, buttons, next, jump, prev, }: FormProps) { const form = useForm({ defaultValues, resolver: zodResolver(validate), }); return (

{heading}

{message}

{content.map((item, i) => ( ))}
{buttons.back && ( )}
); } ``` Each field in `content` is described by an `Item` object and rendered by the `ItemView` component. The back button uses `jump`, since `back` returns where the user came from, not the previous step. The second one is `src/components/review/index.tsx`, with the `Review` component. ```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[]; buttons: { next: string; back: string; }; next: Next>; jump: Jump>; prev: string; status: FormStatus; } export function Review({ heading, message, content, buttons, next, jump, prev, status, }: ReviewProps) { return (

{heading}

{message}

{content.map((item, i) => ( ))}
); } ``` Each entry in `content` is an `Item` with a title, the rows to show, and the id of the form to be edited. The `status` prop tells whether the form is being submitted. 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 { s, Flow } from "@formity/react"; import { z } from "zod"; import type { Steps, FormStep, ReviewStep } from "./types/steps"; import type { FormStatus } from "./types/status"; import { Form } from "./components/form"; import { Review } from "./components/review"; import * as constants from "./constants"; import * as format from "./utils/format"; type Values = UnionToIntersection; type Fields = { profile: { name: string; email: string; jobTitle: string; }; company: { companyName: string; industry: string; companySize: string; }; workspace: { workspaceName: string; timezone: string; language: string; }; }; const profile: FormStep = { id: "profile", label: "Your profile", subtitle: "Name and contact details", zod: z.object({ name: z.string().nonempty("Please enter your full name"), email: z.email("Please enter a valid email address"), jobTitle: z.string().nonempty("Please enter your job title"), }), }; const company: FormStep = { id: "company", label: "Your company", subtitle: "Industry and team size", zod: z.object({ companyName: z.string().nonempty("Please enter your company name"), industry: z.string().nonempty("Please select your industry"), companySize: z.string().nonempty("Please select your company size"), }), }; const workspace: FormStep = { id: "workspace", label: "Your workspace", subtitle: "Name, timezone and language", zod: z.object({ workspaceName: z.string().nonempty("Please enter a workspace name"), timezone: z.string().nonempty("Please select a timezone"), language: z.string().nonempty("Please select a language"), }), }; const review: ReviewStep = { id: "review", label: "Review & launch", subtitle: "Confirm and go live", }; export const steps: Steps = [profile, company, workspace, review]; export type Schema = { render: React.ReactNode; struct: [ s.Jump>, s.Jump>, s.Jump>, s.Jump>>, s.Return, ]; inputs: Values; params: { status: FormStatus; }; }; export const flow: Flow = [ { jump: { id: profile.id, at: { form: { fields: (values) => ({ name: [values.name, []], email: [values.email, []], jobTitle: [values.jobTitle, []], }), render: ({ fields, next, jump }) => (
), }, }, }, }, { jump: { id: company.id, at: { form: { fields: (values) => ({ companyName: [values.companyName, []], industry: [values.industry, []], companySize: [values.companySize, []], }), render: ({ fields, next, jump }) => ( ), }, }, }, }, { jump: { id: workspace.id, at: { form: { fields: (values) => ({ workspaceName: [values.workspaceName, []], timezone: [values.timezone, []], language: [values.language, []], }), render: ({ fields, next, jump }) => ( ), }, }, }, }, { jump: { id: review.id, at: { form: { fields: () => ({}), render: ({ values, params, next, jump }) => ( ), }, }, }, }, { return: (values) => values, }, ]; export const initialValues: Values = { name: "", email: "", jobTitle: "", companyName: "", industry: "", companySize: "", workspaceName: "", timezone: "", language: "", }; ``` Each form is a `FormStep`, with its own Zod schema, and the review step is a `ReviewStep`, with none. The `Values` type merges the fields of the steps into one object, using `UnionToIntersection`. The fourth one is `src/app.tsx`, which renders the form next to the sidebar. ```tsx // src/app.tsx import type { OnReturn, ReturnOutput } from "@formity/react"; import { useState, useCallback } from "react"; import { useFormity } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import { Sidebar } from "./components/sidebar"; import { Done } from "./components/done"; import { steps, flow, initialValues, type Schema } from "./flow"; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(async (output) => { setStatus({ type: "form", submitting: true }); console.log(output); await new Promise((resolve) => setTimeout(resolve, 1000)); setStatus({ type: "done", output }); }, []); if (status.type === "done") { return ( setStatus({ type: "form", submitting: false })} /> ); } return ; } interface FormProps { status: FormStatus; onReturn: OnReturn; } function Form({ status, onReturn }: FormProps) { const form = useFormity({ flow, inputs: initialValues, params: { status }, history: false, onReturn, }); return (
{}} />
{form}
); } ``` The `Sidebar` component receives the index of the step being shown in `current` and the number of completed steps in `completed`. It calls `jump` with the `id` of the step that is clicked. For now it receives fixed values, so the first step is always highlighted and clicking a step does nothing. The steps after the first one that isn't completed are disabled. ## Completed steps The sidebar needs to know how many steps are completed. A step is completed when the form values pass its Zod schema and those of the previous steps, so we'll check them in order until one fails. For that we'll need values as users type, but Formity only receives them whenever a step is submitted. So we'll keep them in a state of the parent, which the `Form` component updates on every change. To do this, `Form` gets all the steps' values in `values`, and calls `onValuesChange` with them updated. It gets a second type parameter for them, `U`, while `T` is still the type of the step's fields. ```diff // src/components/form/index.tsx @@ -2,13 +2,14 @@ import type { Next, Jump } from "@formity/react"; import type { z } from "zod"; +import { useEffect, useEffectEvent } from "react"; import { useForm, FormProvider } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; -interface FormProps> { +interface FormProps, U extends T> { defaultValues: DefaultValues; validate: z.ZodType; heading: string; @@ -21,9 +22,11 @@ next: Next; jump: Jump; prev: string | null; + values: U; + onValuesChange: (values: U) => void; } -export function Form>({ +export function Form, U extends T>({ defaultValues, validate, heading, @@ -33,12 +36,25 @@ next, jump, prev, -}: FormProps) { + values, + onValuesChange, +}: FormProps) { const form = useForm({ defaultValues, resolver: zodResolver(validate), }); + const onFieldsChange = useEffectEvent(({ values: fields }: { values: T }) => { + onValuesChange({ ...values, ...fields }); + }); + + useEffect(() => { + return form.subscribe({ + formState: { values: true }, + callback: onFieldsChange, + }); + }, [form]); + return ( void; }; }; @@ -99,7 +101,7 @@ email: [values.email, []], jobTitle: [values.jobTitle, []], }), - render: ({ fields, next, jump }) => ( + render: ({ fields, params, next, jump }) => ( ), }, @@ -147,7 +151,7 @@ industry: [values.industry, []], companySize: [values.companySize, []], }), - render: ({ fields, next, jump }) => ( + render: ({ fields, params, next, jump }) => ( ), }, @@ -196,7 +202,7 @@ timezone: [values.timezone, []], language: [values.language, []], }), - render: ({ fields, next, jump }) => ( + render: ({ fields, params, next, jump }) => ( ), }, ``` Finally, in `src/app.tsx` we create the state from `initialValues` and pass it down through `params`. The `Sidebar` then receives `completed`, the number of completed steps, computed from the state. ```diff // src/app.tsx @@ -1,9 +1,10 @@ import type { OnReturn, ReturnOutput } from "@formity/react"; -import { useState, useCallback } from "react"; +import { useState, useCallback, useMemo } from "react"; import { useFormity } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; +import type { FormStep } from "./types/steps"; import { Sidebar } from "./components/sidebar"; import { Done } from "./components/done"; @@ -44,16 +45,34 @@ } function Form({ status, onReturn }: FormProps) { + const [values, setValues] = useState(initialValues); + const form = useFormity({ flow, inputs: initialValues, - params: { status }, + params: { status, values, onValuesChange: setValues }, history: false, onReturn, }); + + const completed = useMemo(() => { + for (let i = 0; i < steps.length - 1; i++) { + const step = steps[i] as FormStep; + if (!step.zod.safeParse(values).success) { + return i; + } + } + return steps.length - 1; + }, [values]); + return (
- {}} /> + {}} + />
{form}
); ``` Since `completed` is computed again whenever `values` changes, the sidebar updates as users type. The review step is left out of the loop, as it has nothing to validate. ## Current step The sidebar also needs to know which step is being shown. With the [`useFormity`](https://formity.app/docs/basic-concepts/use-formity.md) hook, a step can return any value and not just a component. So each step will return its index along with the form. We'll update `src/flow.tsx` to do so. Every `render` function now returns an object, with `step` as the index of the step and `form` as the form. The type of `render` in the `Schema` changes too. ```tsx // src/flow.tsx import type { UnionToIntersection } from "type-fest"; import type { s, Flow } from "@formity/react"; import { z } from "zod"; import type { Steps, FormStep, ReviewStep } from "./types/steps"; import type { FormStatus } from "./types/status"; import { Form } from "./components/form"; import { Review } from "./components/review"; import * as constants from "./constants"; import * as format from "./utils/format"; type Values = UnionToIntersection; type Fields = { profile: { name: string; email: string; jobTitle: string; }; company: { companyName: string; industry: string; companySize: string; }; workspace: { workspaceName: string; timezone: string; language: string; }; }; const profile: FormStep = { id: "profile", label: "Your profile", subtitle: "Name and contact details", zod: z.object({ name: z.string().nonempty("Please enter your full name"), email: z.email("Please enter a valid email address"), jobTitle: z.string().nonempty("Please enter your job title"), }), }; const company: FormStep = { id: "company", label: "Your company", subtitle: "Industry and team size", zod: z.object({ companyName: z.string().nonempty("Please enter your company name"), industry: z.string().nonempty("Please select your industry"), companySize: z.string().nonempty("Please select your company size"), }), }; const workspace: FormStep = { id: "workspace", label: "Your workspace", subtitle: "Name, timezone and language", zod: z.object({ workspaceName: z.string().nonempty("Please enter a workspace name"), timezone: z.string().nonempty("Please select a timezone"), language: z.string().nonempty("Please select a language"), }), }; const review: ReviewStep = { id: "review", label: "Review & launch", subtitle: "Confirm and go live", }; export const steps: Steps = [profile, company, workspace, review]; export type Schema = { render: { step: number; form: React.ReactNode }; struct: [ s.Jump>, s.Jump>, s.Jump>, s.Jump>>, s.Return, ]; inputs: Values; params: { status: FormStatus; values: Values; onValuesChange: (values: Values) => void; }; }; export const flow: Flow = [ { jump: { id: profile.id, at: { form: { fields: (values) => ({ name: [values.name, []], email: [values.email, []], jobTitle: [values.jobTitle, []], }), render: ({ fields, params, next, jump }) => ({ step: 0, form: ( ), }), }, }, }, }, { jump: { id: company.id, at: { form: { fields: (values) => ({ companyName: [values.companyName, []], industry: [values.industry, []], companySize: [values.companySize, []], }), render: ({ fields, params, next, jump }) => ({ step: 1, form: ( ), }), }, }, }, }, { jump: { id: workspace.id, at: { form: { fields: (values) => ({ workspaceName: [values.workspaceName, []], timezone: [values.timezone, []], language: [values.language, []], }), render: ({ fields, params, next, jump }) => ({ step: 2, form: ( ), }), }, }, }, }, { jump: { id: review.id, at: { form: { fields: () => ({}), render: ({ values, params, next, jump }) => ({ step: 3, form: ( ), }), }, }, }, }, { return: (values) => values, }, ]; export const initialValues: Values = { name: "", email: "", jobTitle: "", companyName: "", industry: "", companySize: "", workspaceName: "", timezone: "", language: "", }; ``` The hook always returns what the current step renders, so in `src/app.tsx` it now gives us this object. We take `step` and `form` from it, and pass the first one to the `Sidebar` as `current`. ```diff // src/app.tsx @@ -47,7 +47,7 @@ function Form({ status, onReturn }: FormProps) { const [values, setValues] = useState(initialValues); - const form = useFormity({ + const { step: current, form } = useFormity({ flow, inputs: initialValues, params: { status, values, onValuesChange: setValues }, @@ -69,7 +69,7 @@
{}} /> ``` ## Sidebar jumps The sidebar can't call `jump` directly, since only the `render` function of each form element receives it. So the step being shown will use `useImperativeHandle` to expose a `jump` method through a ref. We start with the `Form` component, which receives the ref and exposes the `jump` method through it. The method jumps to the given step, passing the current field values so they're saved in the flow. ```diff // src/components/form/index.tsx @@ -2,7 +2,7 @@ import type { Next, Jump } from "@formity/react"; import type { z } from "zod"; -import { useEffect, useEffectEvent } from "react"; +import { useEffect, useEffectEvent, useImperativeHandle } from "react"; import { useForm, FormProvider } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; @@ -24,6 +24,7 @@ prev: string | null; values: U; onValuesChange: (values: U) => void; + ref: React.Ref<{ jump: (id: string) => void }>; } export function Form, U extends T>({ @@ -38,6 +39,7 @@ prev, values, onValuesChange, + ref, }: FormProps) { const form = useForm({ defaultValues, @@ -55,6 +57,14 @@ }); }, [form]); + useImperativeHandle( + ref, + () => ({ + jump: (id) => jump(id, form.getValues()), + }), + [form, jump], + ); + return ( >; prev: string; status: FormStatus; + ref: React.Ref<{ jump: (id: string) => void }>; } export function Review({ @@ -27,7 +30,16 @@ jump, prev, status, + ref, }: ReviewProps) { + useImperativeHandle( + ref, + () => ({ + jump: (id) => jump(id, {}), + }), + [jump], + ); + return (
``` Now we add `ref` to `params`, so that the `flow` can pass it to the `Form` and `Review` components. ```diff // src/flow.tsx @@ -87,6 +87,7 @@ status: FormStatus; values: Values; onValuesChange: (values: Values) => void; + ref: React.Ref<{ jump: (id: string) => void }>; }; }; @@ -137,6 +138,7 @@ prev={null} values={params.values} onValuesChange={params.onValuesChange} + ref={params.ref} /> ), }), @@ -191,6 +193,7 @@ prev={profile.id} values={params.values} onValuesChange={params.onValuesChange} + ref={params.ref} /> ), }), @@ -245,6 +248,7 @@ prev={company.id} values={params.values} onValuesChange={params.onValuesChange} + ref={params.ref} /> ), }), @@ -317,6 +321,7 @@ jump={jump} prev={workspace.id} status={params.status} + ref={params.ref} /> ), }), ``` Finally, we create the ref in `src/app.tsx` and pass it through `params`. When a step of the sidebar is clicked, we call the `jump` method of the ref with its `id`. ```tsx // src/app.tsx import type { OnReturn, ReturnOutput } from "@formity/react"; import { useState, useCallback, useMemo, useRef } from "react"; import { useFormity } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import type { FormStep } from "./types/steps"; import { Sidebar } from "./components/sidebar"; import { Done } from "./components/done"; import { steps, flow, initialValues, type Schema } from "./flow"; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(async (output) => { setStatus({ type: "form", submitting: true }); console.log(output); await new Promise((resolve) => setTimeout(resolve, 1000)); setStatus({ type: "done", output }); }, []); if (status.type === "done") { return ( setStatus({ type: "form", submitting: false })} /> ); } return ; } interface FormProps { status: FormStatus; onReturn: OnReturn; } function Form({ status, onReturn }: FormProps) { const [values, setValues] = useState(initialValues); const ref = useRef<{ jump: (id: string) => void }>(null); const { step: current, form } = useFormity({ flow, inputs: initialValues, params: { status, values, onValuesChange: setValues, ref }, history: false, onReturn, }); const completed = useMemo(() => { for (let i = 0; i < steps.length - 1; i++) { const step = steps[i] as FormStep; if (!step.zod.safeParse(values).success) { return i; } } return steps.length - 1; }, [values]); return (
ref.current?.jump(step)} />
{form}
); } ``` The ref always has the `jump` method of the step being shown, since it's the only step being rendered. The sidebar only lets users click the completed steps and the next one, so they can't skip steps. # Repeating steps Source: https://formity.app/docs/guides/repeating-steps > Learn how to repeat steps in a multi-step form. ## Initial steps We'll show you how to repeat steps in a multi-step form. To follow along, start by cloning the repository below, which contains the code we'll use as the starting point. ```bash git clone https://github.com/martiserra99/formity-react-hook-form ``` Then install the dependencies. ```bash 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](https://formity.app/docs/use-with-form-libraries/react-hook-form.md) 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 is one file that we'll update, and the rest of the repo stays as it is. It 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` With this code, the number of steps is fixed. There's no way yet to repeat a step, which is what we need to ask the same question about each item of a list. ## Repeating steps Repeating steps is useful when you need to ask the same question about each item in a dynamic list. The [loop](https://formity.app/docs/flow-elements/loop.md) element handles this, since it repeats a set of flow elements while a condition is `true`. Now we'll replace the flow in `src/app.tsx` with one where the user picks some technologies and rates their experience with each one. In the first step the user selects the `technologies`. Then, a [variables](https://formity.app/docs/flow-elements/variables.md) element creates `i`, the index of the current technology, and `results`, the array where we'll save the answers. The loop then goes through the technologies one by one. In each iteration it asks for the experience with the current one, adds the answer to `results` and increases `i`. ```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<{ technologies: string[] }>, s.Variables<{ questions: Record; i: number; results: { technology: string; experience: string }[]; }>, s.Loop< [ s.Variables<{ technology: string }>, s.Form<{ experience: string }>, s.Variables<{ i: number; results: { technology: string; experience: string }[]; }>, ] >, s.Return<{ results: { technology: string; experience: string }[]; }>, ]; inputs: Record; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ technologies: [[], []], }), render: ({ fields, params, back, next }) => ( ), }, }, { variables: () => ({ questions: { react: "What is your experience with React?", vue: "What is your experience with Vue?", angular: "What is your experience with Angular?", svelte: "What is your experience with Svelte?", }, i: 0, results: [], }), }, { loop: { while: ({ i, technologies }) => i < technologies.length, do: [ { variables: ({ i, technologies }) => ({ technology: technologies[i], }), }, { form: { fields: ({ i }) => ({ experience: ["junior", [i]], }), render: ({ fields, values, params, back, next }) => ( ), }, }, { variables: ({ i, technology, experience, results }) => ({ i: i + 1, results: [...results, { technology, experience }], }), }, ], }, }, { return: ({ results }) => ({ results }), }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` All the iterations share the same form element, so the `key` of `Form` is `values.i` rather than a fixed string, and React mounts a new form in each one. The `experience` field also requires an array that changes in each iteration, which is why we use `[i]`. If it were empty, the field would show the answer from the previous iteration. # Using modules Source: https://formity.app/docs/guides/using-modules > Learn how to include external modules in the flow. ## Initial steps We'll show you how to create external modules to include in our flow. To follow along, start by cloning the repository below, which contains the code we'll use as the starting point. ```bash git clone https://github.com/martiserra99/formity-react-hook-form ``` Then install the dependencies. ```bash 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](https://formity.app/docs/use-with-form-libraries/react-hook-form.md) 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 is one file that we'll update, and the rest of the repo stays as it is. It 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` Here the whole flow is a single list, with both forms and the condition defined side by side. As the flow grows it becomes harder to follow, and no part of it can be reused in another flow. ## Using modules The [module](https://formity.app/docs/flow-elements/module.md) element includes a nested flow inside the main one, which keeps the code organized and lets us reuse parts of a flow in other flows. We'll split the flow in `src/app.tsx` into three modules, one for each form and one for the condition. The elements inside them and the `App` component stay the same. ```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.Module<{ render: React.ReactNode; struct: [s.Form<{ name: string; surname: string; age: number }>]; inputs: Record; values: Record; params: { status: FormStatus; }; }>, s.Module<{ render: React.ReactNode; struct: [s.Form<{ softwareDeveloper: string }>]; inputs: Record; values: Record; params: { status: FormStatus; }; }>, s.Module<{ render: React.ReactNode; struct: [ 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; values: { name: string; surname: string; age: number; softwareDeveloper: string; }; params: { status: FormStatus; }; }>, ]; inputs: Record; params: { status: FormStatus; }; }; const flow: Flow = [ { module: [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, ], }, { module: [ { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, ], }, { module: [ { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ], }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` In the `Schema`, each module is declared with `s.Module`. Its schema has the same properties as the flow's, plus `values` for the values from previous steps that the module uses. The schema of a module must be compatible with the schema of the parent flow. Specifically: - `render` must match the flow's `render`. - `inputs` must be a subset of the flow's `inputs`. - `values` must be a subset of the flow's values at that point. - `params` must be a subset of the flow's `params`. ## Separate files Each module can be defined in its own file, which is where modules are most useful. We'll create one file per module in a `src/modules` folder, and import them in `src/app.tsx`. Each file exports the module's `Schema` and its nested flow, declared with `Module` instead of `Flow`. We call it `subFlow` because frameworks like Next.js don't allow variables named `module`. Create `src/modules/yourself.tsx` with the first module. ```tsx // src/modules/yourself.tsx import type { Module, s } from "@formity/react"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import type { FormStatus } from "../types/status"; import { Form } from "../components/form"; export type Schema = { render: React.ReactNode; struct: [s.Form<{ name: string; surname: string; age: number }>]; inputs: Record; values: Record; params: { status: FormStatus; }; }; export const subFlow: Module = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, ]; ``` Create `src/modules/software-developer.tsx` with the second module. ```tsx // src/modules/software-developer.tsx import type { Module, s } from "@formity/react"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import type { FormStatus } from "../types/status"; import { Form } from "../components/form"; export type Schema = { render: React.ReactNode; struct: [s.Form<{ softwareDeveloper: string }>]; inputs: Record; values: Record; params: { status: FormStatus; }; }; export const subFlow: Module = [ { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, ]; ``` Create `src/modules/condition.tsx` with the third module. ```tsx // src/modules/condition.tsx import type { Module, s } from "@formity/react"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import type { FormStatus } from "../types/status"; import { Form } from "../components/form"; export type Schema = { render: React.ReactNode; struct: [ 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; values: { name: string; surname: string; age: number; softwareDeveloper: string; }; params: { status: FormStatus; }; }; export const subFlow: Module = [ { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; ``` Finally, update `src/app.tsx` to import the modules and use them in the flow. We import each file as a namespace, so that the `Schema` and `subFlow` of each module don't clash with each other. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type s, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import { Done } from "./components/done"; import * as yourself from "./modules/yourself"; import * as softwareDeveloper from "./modules/software-developer"; import * as condition from "./modules/condition"; type Schema = { render: React.ReactNode; struct: [ s.Module, s.Module, s.Module, ]; inputs: Record; params: { status: FormStatus; }; }; const flow: Flow = [ { module: yourself.subFlow }, { module: softwareDeveloper.subFlow }, { module: condition.subFlow }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` Each file's `Schema` is passed to `s.Module` in the `Schema` of the flow, and its `subFlow` is passed to the module element in the `flow`. # React Hook Form Source: https://formity.app/docs/use-with-form-libraries/react-hook-form > Learn how to integrate Formity with React Hook Form with an example implementation. ## Initial steps Formity works alongside [React Hook Form](https://react-hook-form.com/). To see how the integration works, clone this repository. ```bash git clone https://github.com/martiserra99/formity-react-hook-form ``` Then install the dependencies. ```bash npm install ``` It uses `@formity/react`, `react-hook-form`, `@hookform/resolvers` and `zod`. ## App component The flow is defined in `src/app.tsx`, and every form element renders the `Form` 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => ( ), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` The `content` prop is the list of fields that the step shows, and `status` tells the form if the output is being submitted. The `Status` and `FormStatus` types are in `src/types/status.ts`. ```tsx // src/types/status.ts export type Status = FormStatus | DoneStatus; export type FormStatus = { type: "form"; submitting: boolean; }; export type DoneStatus = { type: "done"; output: T; }; ``` ## Form component The `Form` component in `src/components/form/index.tsx` connects Formity and React Hook Form. ```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> { defaultValues: DefaultValues; resolver: Resolver; heading: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; status: FormStatus; } export function Form>({ defaultValues, resolver, heading, content, buttons, back, next, status, }: FormProps) { const form = useForm({ defaultValues, resolver }); return (

{heading}

{content.map((field, index) => ( ))}
{buttons.back && ( )}
); } ``` It creates the form with `useForm` and connects it to `back` and `next`. The type parameter `T` is the values of the step, so they match the ones in the `Schema`. The fields are inside `FormProvider`, so each one of them can get the form with `useFormContext`. Then it uses `Controller` to read its value from the form and to update it when the user types. ```tsx // src/components/form/item/input.tsx import { useId } from "react"; import { useFormContext, Controller } from "react-hook-form"; import * as Label from "@radix-ui/react-label"; import { inputVariants, errorVariants } from "./classes"; export interface Input { type: "input"; name: string; label: string; placeholder: string; optional?: boolean; } export function InputView({ name, label, placeholder, optional }: Input) { const id = useId(); const { control, formState } = useFormContext(); const error = formState.errors[name] as { message: string } | undefined; return ( (
<>{label} {optional && ( {" "} — optional )} {error && {error.message}}
)} /> ); } ``` The `name` of each field has to be one of the names used in `fields`, and its value needs to have the same type as in the `Schema`. ## Default values Each form element passes its `fields` to `Form` as `defaultValues`. ```tsx // src/app.tsx { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => (
), }, } ``` Then `Form` gives them to `useForm`. ```tsx // src/components/form/index.tsx const form = useForm({ defaultValues, resolver }); ``` The first time a step is shown, `fields` just contains the default values defined in the form element. When the user returns to a step, it contains the values entered before. ## Validation Each form element passes its own `resolver`, created with `zodResolver` and Zod. ```tsx // src/app.tsx { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, } ``` Then `Form` gives it to `useForm`. ```tsx // src/components/form/index.tsx const form = useForm({ defaultValues, resolver }); ``` The values are validated when the form is submitted, and after that every time they change. ## Next step The `next` function is passed to `handleSubmit` in the `form` element. ```tsx // src/components/form/index.tsx {/* ... */}
``` React Hook Form only calls it once the values are valid, so the flow moves to the next step with them. ## Previous step The `back` function is called with `getValues` when the back button is clicked. ```tsx // src/components/form/index.tsx ``` It doesn't go through `handleSubmit`, so the user can always go back even if the values are not valid. Formity keeps the values, and the step starts with them when the user returns to it. # Formik Source: https://formity.app/docs/use-with-form-libraries/formik > Learn how to integrate Formity with Formik with an example implementation. ## Initial steps Formity works alongside [Formik](https://formik.org/). To see how the integration works, clone this repository. ```bash git clone https://github.com/martiserra99/formity-formik ``` Then install the dependencies. ```bash npm install ``` It uses `@formity/react`, `formik` and `yup`. ## App component The flow is defined in `src/app.tsx`, and every form element renders the `Form` component. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type s, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import * as yup from "yup"; 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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, back, next }) => (
), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` The `content` prop is the list of fields that the step shows, and `status` tells the form if the output is being submitted. The `Status` and `FormStatus` types are in `src/types/status.ts`. ```tsx // src/types/status.ts export type Status = FormStatus | DoneStatus; export type FormStatus = { type: "form"; submitting: boolean; }; export type DoneStatus = { type: "done"; output: T; }; ``` ## Form component The `Form` component in `src/components/form/index.tsx` connects Formity and Formik. ```tsx // src/components/form/index.tsx import type { AnyObjectSchema } from "yup"; import type { Back, Next } from "@formity/react"; import { useFormik, FormikProvider } from "formik"; import type { FormStatus } from "@/types/status"; import { ItemView, type Item } from "./item"; import { Button } from "../button"; interface FormProps> { defaultValues: T; validationSchema: AnyObjectSchema; heading: string; content: Item[]; buttons: { back: string | null; next: string; }; back: Back; next: Next; status: FormStatus; } export function Form>({ defaultValues, validationSchema, heading, content, buttons, back, next, status, }: FormProps) { const formik = useFormik({ initialValues: defaultValues, validationSchema, onSubmit: next, }); return (

{heading}

{content.map((field, index) => ( ))}
{buttons.back && ( )}
); } ``` It creates the form with `useFormik` and connects it to `back` and `next`. The type parameter `T` is the values of the step, so they match the ones in the `Schema`. The fields are inside `FormikProvider`, so each one of them can use `useField` to read its value from the form and to update it when the user types. ```tsx // src/components/form/item/input.tsx import { useId } from "react"; import { useField } from "formik"; import * as Label from "@radix-ui/react-label"; import { inputVariants, errorVariants } from "./classes"; export interface Input { type: "input"; name: string; label: string; placeholder: string; optional?: boolean; } export function InputView({ name, label, placeholder, optional }: Input) { const id = useId(); const [field, meta] = useField(name); const error = meta.touched && meta.error ? meta.error : undefined; return (
<>{label} {optional && ( {" "} — optional )} {error && {error}}
); } ``` The `name` of each field has to be one of the names used in `fields`, and its value needs to have the same type as in the `Schema`. ## Default values Each form element passes its `fields` to `Form` as `defaultValues`. ```tsx // src/app.tsx { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => (
), }, } ``` Then `Form` gives them to `useFormik` as `initialValues`. ```tsx // src/components/form/index.tsx const formik = useFormik({ initialValues: defaultValues, validationSchema, onSubmit: next, }); ``` The first time a step is shown, `fields` just contains the default values defined in the form element. When the user returns to a step, it contains the values entered before. ## Validation Each form element passes its own `validationSchema`, created with Yup. ```tsx // src/app.tsx { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, } ``` Then `Form` gives it to `useFormik`. ```tsx // src/components/form/index.tsx const formik = useFormik({ initialValues: defaultValues, validationSchema, onSubmit: next, }); ``` The values are validated when they change, when a field loses focus and when the form is submitted. Each field shows its error once it loses focus or the form is submitted. ## Next step The `next` function is passed to `useFormik` as `onSubmit`, and the `form` uses `handleSubmit`. ```tsx // src/components/form/index.tsx const formik = useFormik({ initialValues: defaultValues, validationSchema, onSubmit: next, }); return ( {/* ... */}
); ``` Formik only calls it once the values are valid, so the flow moves to the next step with them. ## Previous step The `back` function is called with `formik.values` when the back button is clicked. ```tsx // src/components/form/index.tsx ``` It doesn't go through `handleSubmit`, so the user can always go back even if the values are not valid. Formity keeps the values, and the step starts with them when the user returns to it. # TanStack Form Source: https://formity.app/docs/use-with-form-libraries/tanstack-form > Learn how to integrate Formity with TanStack Form with an example implementation. ## Initial steps Formity works alongside [TanStack Form](https://tanstack.com/form/latest). To see how the integration works, clone this repository. ```bash git clone https://github.com/martiserra99/formity-tanstack-form ``` Then install the dependencies. ```bash npm install ``` It uses `@formity/react`, `@tanstack/react-form` and `zod`. ## App component The flow is defined in `src/app.tsx`, and every form element renders its own form component. ```tsx // src/app.tsx import { useCallback, useState } from "react"; import { Formity, type s, type Flow, type OnReturn, type ReturnOutput, } from "@formity/react"; import type { Status, FormStatus } from "./types/status"; import { YourselfForm } from "./components/forms/yourself-form"; import { SoftwareDeveloperForm } from "./components/forms/software-developer-form"; import { ExpertiseForm } from "./components/forms/expertise-form"; import { InterestedForm } from "./components/forms/interested-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; params: { status: FormStatus; }; }; const flow: Flow = [ { form: { fields: () => ({ name: ["", []], surname: ["", []], age: [20, []], }), render: ({ fields, params, next }) => ( ), }, }, { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { condition: { if: ({ softwareDeveloper }) => softwareDeveloper === "yes", then: [ { form: { fields: () => ({ expertise: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, expertise }) => ({ name, surname, age, softwareDeveloper: true, expertise, }), }, ], else: [ { form: { fields: () => ({ interested: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, }, { return: ({ name, surname, age, interested }) => ({ name, surname, age, softwareDeveloper: false, interested, }), }, ], }, }, ]; export default function App() { const [status, setStatus] = useState>>({ type: "form", submitting: false, }); const onReturn = useCallback>(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 ( setStatus({ type: "form", submitting: false })} /> ); } return ( flow={flow} params={{ status }} onReturn={onReturn} /> ); } ``` The `status` prop tells the form when the output is being submitted, so it can disable its buttons then. The `Status` and `FormStatus` types are in `src/types/status.ts`. ```tsx // src/types/status.ts export type Status = FormStatus | DoneStatus; export type FormStatus = { type: "form"; submitting: boolean; }; export type DoneStatus = { type: "done"; output: T; }; ``` ## Form components Each step has its own component in `src/components/forms`, and each one of them connects Formity and TanStack Form. They all follow the same structure, so we'll look at `SoftwareDeveloperForm`. ```tsx // src/components/forms/software-developer-form.tsx import type { Back, Next } from "@formity/react"; import { useForm } from "@tanstack/react-form"; import { z } from "zod"; import type { FormStatus } from "@/types/status"; import { Select } from "./fields/select"; import { Button } from "../button"; const schema = z.object({ softwareDeveloper: z.string().nonempty("Required"), }); type Values = { softwareDeveloper: string }; interface Props { defaultValues: Values; back: Back; next: Next; status: FormStatus; } export function SoftwareDeveloperForm({ defaultValues, back, next, status, }: Props) { const form = useForm({ defaultValues, validators: { onChange: schema }, onSubmit: async ({ value }) => next(value), }); return (
{ e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} className="flex h-screen w-full items-center justify-center px-4 py-8" autoComplete="off" >

Are you a software developer?

{(field) => ( field.handleChange(e.target.value)} onBlur={field.handleBlur} /> {error && {error}}
); } ``` The `FormField` type and the `getError` function are both defined in `src/types/form-field.ts`. The type contains what these components need, and the function returns the error. ```tsx // src/types/form-field.ts export interface FormField { state: { value: T; meta: { isTouched: boolean; errors: unknown[]; }; }; handleChange: (value: T) => void; handleBlur: () => void; } export function getError(field: { state: { meta: { isTouched: boolean; errors: unknown[] } }; }): string | undefined { if (!field.state.meta.isTouched || field.state.meta.errors.length === 0) { return undefined; } const error = field.state.meta.errors[0]!; if (typeof error === "object" && "message" in error) { return error.message as string; } return undefined; } ``` The `name` of each field has to be one of the names used in `fields`, and its value needs to have the same type as in the `Schema`. ## Default values Each form element passes its `fields` to its form component as `defaultValues`. ```tsx // src/app.tsx { form: { fields: () => ({ softwareDeveloper: ["", []], }), render: ({ fields, params, back, next }) => ( ), }, } ``` Then the component gives them to `useForm`. ```tsx // src/components/forms/software-developer-form.tsx const form = useForm({ defaultValues, validators: { onChange: schema }, onSubmit: async ({ value }) => next(value), }); ``` The first time a step is shown, `fields` just contains the default values defined in the form element. When the user returns to a step, it contains the values entered before. ## Validation Each form component defines its own `schema` with Zod. ```tsx // src/components/forms/software-developer-form.tsx const schema = z.object({ softwareDeveloper: z.string().nonempty("Required"), }); ``` Then the schema is passed to `useForm` as the `onChange` validator. ```tsx // src/components/forms/software-developer-form.tsx const form = useForm({ defaultValues, validators: { onChange: schema }, onSubmit: async ({ value }) => next(value), }); ``` The values are validated every time they change and when the form is submitted. Each field only shows its error once it has been touched, and submitting the form touches all of them. ## Next step The `next` function is called in `onSubmit`, and the `form` element calls `handleSubmit`. ```tsx // src/components/forms/software-developer-form.tsx const form = useForm({ defaultValues, validators: { onChange: schema }, onSubmit: async ({ value }) => next(value), }); return ( { e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} className="flex h-screen w-full items-center justify-center px-4 py-8" autoComplete="off" > {/* ... */} ); ``` TanStack Form only calls `onSubmit` once the values are valid, so the flow moves on with them. ## Previous step The `back` function is called with `form.state.values` when the back button is clicked. ```tsx // src/components/forms/software-developer-form.tsx ``` It doesn't go through `handleSubmit`, so the user can always go back even if the values are not valid. Formity keeps the values, and the step starts with them when the user returns to it. # GitHub repository Source: https://formity.app/docs/previous-versions/github-repository > Information about where to find the documentation for the previous versions. ## GitHub repository In this [GitHub repository](https://github.com/martiserra99/formity-prev-docs) you can find the documentation for the previous versions of Formity.