Guides
Sidebar navigation
Learn how to add a sidebar that lets users jump back to any previously completed step.
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.
git clone https://github.com/martiserra99/formity-sidebar-navigation
Then install the dependencies.
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.
// 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<T extends Record<string, unknown>> {
defaultValues: DefaultValues<T>;
validate: z.ZodType<T, T>;
heading: string;
message: string;
content: Item[];
buttons: {
next: string;
back: string | null;
};
next: Next<T>;
jump: Jump<T>;
prev: string | null;
}
export function Form<T extends Record<string, unknown>>({
defaultValues,
validate,
heading,
message,
content,
buttons,
next,
jump,
prev,
}: FormProps<T>) {
const form = useForm({
defaultValues,
resolver: zodResolver(validate),
});
return (
<form
noValidate
autoComplete="off"
onSubmit={form.handleSubmit(next)}
className="flex flex-1 flex-col overflow-hidden"
>
<FormProvider {...form}>
<div className="flex-1 overflow-y-auto px-12 pt-12 pb-8">
<div className="max-w-lg">
<div className="mb-10">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">
{heading}
</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="mb-8 flex flex-col gap-8">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-8">
{buttons.back && (
<Button
type="button"
variant="secondary"
onClick={() => jump(prev, form.getValues())}
>
{buttons.back}
</Button>
)}
<Button type="submit" variant="primary">
{buttons.next}
</Button>
</div>
</div>
</div>
</FormProvider>
</form>
);
}
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.
// 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<Record<never, never>>;
jump: Jump<Record<never, never>>;
prev: string;
status: FormStatus;
}
export function Review({
heading,
message,
content,
buttons,
next,
jump,
prev,
status,
}: ReviewProps) {
return (
<div className="flex flex-1 flex-col overflow-hidden">
<div className="flex-1 overflow-y-auto px-12 pt-12 pb-8">
<div className="max-w-lg">
<div className="mb-10">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">
{heading}
</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="mb-8 flex flex-col gap-4">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-8">
<Button
type="button"
variant="secondary"
disabled={status.submitting}
onClick={() => jump(prev, {})}
>
{buttons.back}
</Button>
<Button
type="submit"
variant="primary"
onClick={() => next({})}
disabled={status.submitting}
>
{status.submitting ? "Submitting..." : buttons.next}
</Button>
</div>
</div>
</div>
</div>
);
}
Each entry in content is an Item with a title, the rows to show, and the id of the form to be edited. The status prop tells whether the form is being submitted.
The third one is src/flow.tsx, which contains the Schema and the flow.
// 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<Fields[keyof Fields]>;
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<Fields["profile"]> = {
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<Fields["company"]> = {
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<Fields["workspace"]> = {
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.Form<Fields["profile"]>>,
s.Jump<s.Form<Fields["company"]>>,
s.Jump<s.Form<Fields["workspace"]>>,
s.Jump<s.Form<Record<never, never>>>,
s.Return<Values>,
];
inputs: Values;
params: {
status: FormStatus;
};
};
export const flow: Flow<Schema> = [
{
jump: {
id: profile.id,
at: {
form: {
fields: (values) => ({
name: [values.name, []],
email: [values.email, []],
jobTitle: [values.jobTitle, []],
}),
render: ({ fields, next, jump }) => (
<Form
key={profile.id}
defaultValues={fields}
validate={profile.zod}
heading="Tell us about yourself"
message="We'll use this to personalise your experience."
content={[
{
type: "input",
name: "name",
label: "Full name",
placeholder: "Jane Smith",
},
{
type: "input",
name: "email",
label: "Work email",
placeholder: "jane@company.com",
inputType: "email",
},
{
type: "input",
name: "jobTitle",
label: "Job title",
placeholder: "Product Manager",
},
]}
buttons={{ back: null, next: "Continue" }}
next={next}
jump={jump}
prev={null}
/>
),
},
},
},
},
{
jump: {
id: company.id,
at: {
form: {
fields: (values) => ({
companyName: [values.companyName, []],
industry: [values.industry, []],
companySize: [values.companySize, []],
}),
render: ({ fields, next, jump }) => (
<Form
key={company.id}
defaultValues={fields}
validate={company.zod}
heading="About your company"
message="Help us understand the context you're working in."
content={[
{
type: "input",
name: "companyName",
label: "Company name",
placeholder: "Acme Inc.",
},
{
type: "select",
name: "industry",
label: "Industry",
placeholder: "Select an industry",
options: constants.industries,
},
{
type: "select",
name: "companySize",
label: "Company size",
placeholder: "Select a size",
options: constants.companySizes,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={profile.id}
/>
),
},
},
},
},
{
jump: {
id: workspace.id,
at: {
form: {
fields: (values) => ({
workspaceName: [values.workspaceName, []],
timezone: [values.timezone, []],
language: [values.language, []],
}),
render: ({ fields, next, jump }) => (
<Form
key={workspace.id}
defaultValues={fields}
validate={workspace.zod}
heading="Set up your workspace"
message="Give your workspace a name and configure your region."
content={[
{
type: "input",
name: "workspaceName",
label: "Workspace name",
placeholder: "My Workspace",
},
{
type: "select",
name: "timezone",
label: "Timezone",
placeholder: "Select a timezone",
options: constants.timezones,
},
{
type: "select",
name: "language",
label: "Language",
placeholder: "Select a language",
options: constants.languages,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={company.id}
/>
),
},
},
},
},
{
jump: {
id: review.id,
at: {
form: {
fields: () => ({}),
render: ({ values, params, next, jump }) => (
<Review
key={review.id}
heading="Review & launch"
message="Everything look right? Launch your workspace."
content={[
{
text: "Profile",
rows: [
{ label: "Full name", value: format.text(values.name) },
{ label: "Work email", value: format.text(values.email) },
{
label: "Job title",
value: format.text(values.jobTitle),
},
],
},
{
text: "Company",
rows: [
{
label: "Company name",
value: format.text(values.companyName),
},
{
label: "Industry",
value: format.industry(values.industry),
},
{
label: "Company size",
value: format.companySize(values.companySize),
},
],
},
{
text: "Workspace",
rows: [
{
label: "Workspace name",
value: format.text(values.workspaceName),
},
{
label: "Timezone",
value: format.timezone(values.timezone),
},
{
label: "Language",
value: format.language(values.language),
},
],
},
]}
buttons={{ back: "Back", next: "Launch workspace" }}
next={next}
jump={jump}
prev={workspace.id}
status={params.status}
/>
),
},
},
},
},
{
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.
// 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<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(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 (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
function Form({ status, onReturn }: FormProps) {
const form = useFormity({
flow,
inputs: initialValues,
params: { status },
history: false,
onReturn,
});
return (
<div className="@container flex h-screen w-full overflow-hidden bg-white">
<Sidebar steps={steps} current={0} completed={0} jump={() => {}} />
<main className="flex flex-1 flex-col overflow-hidden">{form}</main>
</div>
);
}
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.
// 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 { 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<T extends Record<string, unknown>, U extends T> {
defaultValues: DefaultValues<T>;
validate: z.ZodType<T, T>;
heading: string;
message: string;
content: Item[];
buttons: {
next: string;
back: string | null;
};
next: Next<T>;
jump: Jump<T>;
prev: string | null;
values: U;
onValuesChange: (values: U) => void;
}
export function Form<T extends Record<string, unknown>, U extends T>({
defaultValues,
validate,
heading,
message,
content,
buttons,
next,
jump,
prev,
values,
onValuesChange,
}: FormProps<T, U>) {
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 (
<form
noValidate
autoComplete="off"
onSubmit={form.handleSubmit(next)}
className="flex flex-1 flex-col overflow-hidden"
>
<FormProvider {...form}>
<div className="flex-1 overflow-y-auto px-12 pt-12 pb-8">
<div className="max-w-lg">
<div className="mb-10">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">
{heading}
</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="mb-8 flex flex-col gap-8">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-8">
{buttons.back && (
<Button
type="button"
variant="secondary"
onClick={() => jump(prev, form.getValues())}
>
{buttons.back}
</Button>
)}
<Button type="submit" variant="primary">
{buttons.next}
</Button>
</div>
</div>
</div>
</FormProvider>
</form>
);
}
React Hook Form's subscribe function calls onFieldsChange whenever a field of the step changes. We define it with useEffectEvent, from React 19.2, so that it accesses the latest values.
Each Form is rendered inside the flow, so the two new props have to reach it through params.
// 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<Fields[keyof Fields]>;
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<Fields["profile"]> = {
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<Fields["company"]> = {
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<Fields["workspace"]> = {
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.Form<Fields["profile"]>>,
s.Jump<s.Form<Fields["company"]>>,
s.Jump<s.Form<Fields["workspace"]>>,
s.Jump<s.Form<Record<never, never>>>,
s.Return<Values>,
];
inputs: Values;
params: {
status: FormStatus;
values: Values;
onValuesChange: (values: Values) => void;
};
};
export const flow: Flow<Schema> = [
{
jump: {
id: profile.id,
at: {
form: {
fields: (values) => ({
name: [values.name, []],
email: [values.email, []],
jobTitle: [values.jobTitle, []],
}),
render: ({ fields, params, next, jump }) => (
<Form
key={profile.id}
defaultValues={fields}
validate={profile.zod}
heading="Tell us about yourself"
message="We'll use this to personalise your experience."
content={[
{
type: "input",
name: "name",
label: "Full name",
placeholder: "Jane Smith",
},
{
type: "input",
name: "email",
label: "Work email",
placeholder: "jane@company.com",
inputType: "email",
},
{
type: "input",
name: "jobTitle",
label: "Job title",
placeholder: "Product Manager",
},
]}
buttons={{ back: null, next: "Continue" }}
next={next}
jump={jump}
prev={null}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
},
},
{
jump: {
id: company.id,
at: {
form: {
fields: (values) => ({
companyName: [values.companyName, []],
industry: [values.industry, []],
companySize: [values.companySize, []],
}),
render: ({ fields, params, next, jump }) => (
<Form
key={company.id}
defaultValues={fields}
validate={company.zod}
heading="About your company"
message="Help us understand the context you're working in."
content={[
{
type: "input",
name: "companyName",
label: "Company name",
placeholder: "Acme Inc.",
},
{
type: "select",
name: "industry",
label: "Industry",
placeholder: "Select an industry",
options: constants.industries,
},
{
type: "select",
name: "companySize",
label: "Company size",
placeholder: "Select a size",
options: constants.companySizes,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={profile.id}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
},
},
{
jump: {
id: workspace.id,
at: {
form: {
fields: (values) => ({
workspaceName: [values.workspaceName, []],
timezone: [values.timezone, []],
language: [values.language, []],
}),
render: ({ fields, params, next, jump }) => (
<Form
key={workspace.id}
defaultValues={fields}
validate={workspace.zod}
heading="Set up your workspace"
message="Give your workspace a name and configure your region."
content={[
{
type: "input",
name: "workspaceName",
label: "Workspace name",
placeholder: "My Workspace",
},
{
type: "select",
name: "timezone",
label: "Timezone",
placeholder: "Select a timezone",
options: constants.timezones,
},
{
type: "select",
name: "language",
label: "Language",
placeholder: "Select a language",
options: constants.languages,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={company.id}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
},
},
{
jump: {
id: review.id,
at: {
form: {
fields: () => ({}),
render: ({ values, params, next, jump }) => (
<Review
key={review.id}
heading="Review & launch"
message="Everything look right? Launch your workspace."
content={[
{
text: "Profile",
rows: [
{ label: "Full name", value: format.text(values.name) },
{ label: "Work email", value: format.text(values.email) },
{
label: "Job title",
value: format.text(values.jobTitle),
},
],
},
{
text: "Company",
rows: [
{
label: "Company name",
value: format.text(values.companyName),
},
{
label: "Industry",
value: format.industry(values.industry),
},
{
label: "Company size",
value: format.companySize(values.companySize),
},
],
},
{
text: "Workspace",
rows: [
{
label: "Workspace name",
value: format.text(values.workspaceName),
},
{
label: "Timezone",
value: format.timezone(values.timezone),
},
{
label: "Language",
value: format.language(values.language),
},
],
},
]}
buttons={{ back: "Back", next: "Launch workspace" }}
next={next}
jump={jump}
prev={workspace.id}
status={params.status}
/>
),
},
},
},
},
{
return: (values) => values,
},
];
export const initialValues: Values = {
name: "",
email: "",
jobTitle: "",
companyName: "",
industry: "",
companySize: "",
workspaceName: "",
timezone: "",
language: "",
};
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.
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/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";
import { steps, flow, initialValues, type Schema } from "./flow";
export default function App() {
const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
setStatus({ type: "form", submitting: true });
console.log(output);
await new Promise((resolve) => setTimeout(resolve, 1000));
setStatus({ type: "done", output });
}, []);
if (status.type === "done") {
return (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
function Form({ status, onReturn }: FormProps) {
const [values, setValues] = useState(initialValues);
const form = useFormity({
flow,
inputs: initialValues,
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 (
<div className="@container flex h-screen w-full overflow-hidden bg-white">
<Sidebar
steps={steps}
current={0}
completed={completed}
jump={() => {}}
/>
<main className="flex flex-1 flex-col overflow-hidden">{form}</main>
</div>
);
}
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 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.
// 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<Fields[keyof Fields]>;
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<Fields["profile"]> = {
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<Fields["company"]> = {
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<Fields["workspace"]> = {
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.Form<Fields["profile"]>>,
s.Jump<s.Form<Fields["company"]>>,
s.Jump<s.Form<Fields["workspace"]>>,
s.Jump<s.Form<Record<never, never>>>,
s.Return<Values>,
];
inputs: Values;
params: {
status: FormStatus;
values: Values;
onValuesChange: (values: Values) => void;
};
};
export const flow: Flow<Schema> = [
{
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: (
<Form
key={profile.id}
defaultValues={fields}
validate={profile.zod}
heading="Tell us about yourself"
message="We'll use this to personalise your experience."
content={[
{
type: "input",
name: "name",
label: "Full name",
placeholder: "Jane Smith",
},
{
type: "input",
name: "email",
label: "Work email",
placeholder: "jane@company.com",
inputType: "email",
},
{
type: "input",
name: "jobTitle",
label: "Job title",
placeholder: "Product Manager",
},
]}
buttons={{ back: null, next: "Continue" }}
next={next}
jump={jump}
prev={null}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
}),
},
},
},
},
{
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: (
<Form
key={company.id}
defaultValues={fields}
validate={company.zod}
heading="About your company"
message="Help us understand the context you're working in."
content={[
{
type: "input",
name: "companyName",
label: "Company name",
placeholder: "Acme Inc.",
},
{
type: "select",
name: "industry",
label: "Industry",
placeholder: "Select an industry",
options: constants.industries,
},
{
type: "select",
name: "companySize",
label: "Company size",
placeholder: "Select a size",
options: constants.companySizes,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={profile.id}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
}),
},
},
},
},
{
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: (
<Form
key={workspace.id}
defaultValues={fields}
validate={workspace.zod}
heading="Set up your workspace"
message="Give your workspace a name and configure your region."
content={[
{
type: "input",
name: "workspaceName",
label: "Workspace name",
placeholder: "My Workspace",
},
{
type: "select",
name: "timezone",
label: "Timezone",
placeholder: "Select a timezone",
options: constants.timezones,
},
{
type: "select",
name: "language",
label: "Language",
placeholder: "Select a language",
options: constants.languages,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={company.id}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
}),
},
},
},
},
{
jump: {
id: review.id,
at: {
form: {
fields: () => ({}),
render: ({ values, params, next, jump }) => ({
step: 3,
form: (
<Review
key={review.id}
heading="Review & launch"
message="Everything look right? Launch your workspace."
content={[
{
text: "Profile",
rows: [
{ label: "Full name", value: format.text(values.name) },
{ label: "Work email", value: format.text(values.email) },
{
label: "Job title",
value: format.text(values.jobTitle),
},
],
},
{
text: "Company",
rows: [
{
label: "Company name",
value: format.text(values.companyName),
},
{
label: "Industry",
value: format.industry(values.industry),
},
{
label: "Company size",
value: format.companySize(values.companySize),
},
],
},
{
text: "Workspace",
rows: [
{
label: "Workspace name",
value: format.text(values.workspaceName),
},
{
label: "Timezone",
value: format.timezone(values.timezone),
},
{
label: "Language",
value: format.language(values.language),
},
],
},
]}
buttons={{ back: "Back", next: "Launch workspace" }}
next={next}
jump={jump}
prev={workspace.id}
status={params.status}
/>
),
}),
},
},
},
},
{
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.
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/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";
import { steps, flow, initialValues, type Schema } from "./flow";
export default function App() {
const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
setStatus({ type: "form", submitting: true });
console.log(output);
await new Promise((resolve) => setTimeout(resolve, 1000));
setStatus({ type: "done", output });
}, []);
if (status.type === "done") {
return (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
function Form({ status, onReturn }: FormProps) {
const [values, setValues] = useState(initialValues);
const { step: current, form } = useFormity({
flow,
inputs: initialValues,
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 (
<div className="@container flex h-screen w-full overflow-hidden bg-white">
<Sidebar
steps={steps}
current={current}
completed={completed}
jump={() => {}}
/>
<main className="flex flex-1 flex-col overflow-hidden">{form}</main>
</div>
);
}
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.
// 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 { useEffect, useEffectEvent, useImperativeHandle } 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<T extends Record<string, unknown>, U extends T> {
defaultValues: DefaultValues<T>;
validate: z.ZodType<T, T>;
heading: string;
message: string;
content: Item[];
buttons: {
next: string;
back: string | null;
};
next: Next<T>;
jump: Jump<T>;
prev: string | null;
values: U;
onValuesChange: (values: U) => void;
ref: React.Ref<{ jump: (id: string) => void }>;
}
export function Form<T extends Record<string, unknown>, U extends T>({
defaultValues,
validate,
heading,
message,
content,
buttons,
next,
jump,
prev,
values,
onValuesChange,
ref,
}: FormProps<T, U>) {
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]);
useImperativeHandle(
ref,
() => ({
jump: (id) => jump(id, form.getValues()),
}),
[form, jump],
);
return (
<form
noValidate
autoComplete="off"
onSubmit={form.handleSubmit(next)}
className="flex flex-1 flex-col overflow-hidden"
>
<FormProvider {...form}>
<div className="flex-1 overflow-y-auto px-12 pt-12 pb-8">
<div className="max-w-lg">
<div className="mb-10">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">
{heading}
</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="mb-8 flex flex-col gap-8">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-8">
{buttons.back && (
<Button
type="button"
variant="secondary"
onClick={() => jump(prev, form.getValues())}
>
{buttons.back}
</Button>
)}
<Button type="submit" variant="primary">
{buttons.next}
</Button>
</div>
</div>
</div>
</FormProvider>
</form>
);
}
The Review component does the same, passing an empty object since it has no fields.
// src/components/review/index.tsx
import type { Next, Jump } from "@formity/react";
import type { FormStatus } from "../../types/status";
import { useImperativeHandle } from "react";
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<Record<never, never>>;
jump: Jump<Record<never, never>>;
prev: string;
status: FormStatus;
ref: React.Ref<{ jump: (id: string) => void }>;
}
export function Review({
heading,
message,
content,
buttons,
next,
jump,
prev,
status,
ref,
}: ReviewProps) {
useImperativeHandle(
ref,
() => ({
jump: (id) => jump(id, {}),
}),
[jump],
);
return (
<div className="flex flex-1 flex-col overflow-hidden">
<div className="flex-1 overflow-y-auto px-12 pt-12 pb-8">
<div className="max-w-lg">
<div className="mb-10">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">
{heading}
</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="mb-8 flex flex-col gap-4">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-8">
<Button
type="button"
variant="secondary"
disabled={status.submitting}
onClick={() => jump(prev, {})}
>
{buttons.back}
</Button>
<Button
type="submit"
variant="primary"
onClick={() => next({})}
disabled={status.submitting}
>
{status.submitting ? "Submitting..." : buttons.next}
</Button>
</div>
</div>
</div>
</div>
);
}
Now we add ref to params, so that the flow can pass it to the Form and Review components.
// 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<Fields[keyof Fields]>;
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<Fields["profile"]> = {
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<Fields["company"]> = {
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<Fields["workspace"]> = {
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.Form<Fields["profile"]>>,
s.Jump<s.Form<Fields["company"]>>,
s.Jump<s.Form<Fields["workspace"]>>,
s.Jump<s.Form<Record<never, never>>>,
s.Return<Values>,
];
inputs: Values;
params: {
status: FormStatus;
values: Values;
onValuesChange: (values: Values) => void;
ref: React.Ref<{ jump: (id: string) => void }>;
};
};
export const flow: Flow<Schema> = [
{
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: (
<Form
key={profile.id}
defaultValues={fields}
validate={profile.zod}
heading="Tell us about yourself"
message="We'll use this to personalise your experience."
content={[
{
type: "input",
name: "name",
label: "Full name",
placeholder: "Jane Smith",
},
{
type: "input",
name: "email",
label: "Work email",
placeholder: "jane@company.com",
inputType: "email",
},
{
type: "input",
name: "jobTitle",
label: "Job title",
placeholder: "Product Manager",
},
]}
buttons={{ back: null, next: "Continue" }}
next={next}
jump={jump}
prev={null}
values={params.values}
onValuesChange={params.onValuesChange}
ref={params.ref}
/>
),
}),
},
},
},
},
{
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: (
<Form
key={company.id}
defaultValues={fields}
validate={company.zod}
heading="About your company"
message="Help us understand the context you're working in."
content={[
{
type: "input",
name: "companyName",
label: "Company name",
placeholder: "Acme Inc.",
},
{
type: "select",
name: "industry",
label: "Industry",
placeholder: "Select an industry",
options: constants.industries,
},
{
type: "select",
name: "companySize",
label: "Company size",
placeholder: "Select a size",
options: constants.companySizes,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={profile.id}
values={params.values}
onValuesChange={params.onValuesChange}
ref={params.ref}
/>
),
}),
},
},
},
},
{
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: (
<Form
key={workspace.id}
defaultValues={fields}
validate={workspace.zod}
heading="Set up your workspace"
message="Give your workspace a name and configure your region."
content={[
{
type: "input",
name: "workspaceName",
label: "Workspace name",
placeholder: "My Workspace",
},
{
type: "select",
name: "timezone",
label: "Timezone",
placeholder: "Select a timezone",
options: constants.timezones,
},
{
type: "select",
name: "language",
label: "Language",
placeholder: "Select a language",
options: constants.languages,
},
]}
buttons={{ back: "Back", next: "Continue" }}
next={next}
jump={jump}
prev={company.id}
values={params.values}
onValuesChange={params.onValuesChange}
ref={params.ref}
/>
),
}),
},
},
},
},
{
jump: {
id: review.id,
at: {
form: {
fields: () => ({}),
render: ({ values, params, next, jump }) => ({
step: 3,
form: (
<Review
key={review.id}
heading="Review & launch"
message="Everything look right? Launch your workspace."
content={[
{
text: "Profile",
rows: [
{ label: "Full name", value: format.text(values.name) },
{ label: "Work email", value: format.text(values.email) },
{
label: "Job title",
value: format.text(values.jobTitle),
},
],
},
{
text: "Company",
rows: [
{
label: "Company name",
value: format.text(values.companyName),
},
{
label: "Industry",
value: format.industry(values.industry),
},
{
label: "Company size",
value: format.companySize(values.companySize),
},
],
},
{
text: "Workspace",
rows: [
{
label: "Workspace name",
value: format.text(values.workspaceName),
},
{
label: "Timezone",
value: format.timezone(values.timezone),
},
{
label: "Language",
value: format.language(values.language),
},
],
},
]}
buttons={{ back: "Back", next: "Launch workspace" }}
next={next}
jump={jump}
prev={workspace.id}
status={params.status}
ref={params.ref}
/>
),
}),
},
},
},
},
{
return: (values) => values,
},
];
export const initialValues: Values = {
name: "",
email: "",
jobTitle: "",
companyName: "",
industry: "",
companySize: "",
workspaceName: "",
timezone: "",
language: "",
};
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.
// 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<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(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 (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
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 (
<div className="@container flex h-screen w-full overflow-hidden bg-white">
<Sidebar
steps={steps}
current={current}
completed={completed}
jump={(step) => ref.current?.jump(step)}
/>
<main className="flex flex-1 flex-col overflow-hidden">{form}</main>
</div>
);
}
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.