Form schema
Variables
Learn how the variables element is used in the schema.
Usage
The variables element is used to define variables.
To understand how it is used let's look at this example.
import type { Schema, Form, Return, Variables } from "@formity/react";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Step,
Layout,
Row,
TextField,
NumberField,
NextButton,
} from "./components";
import { MultiStep } from "./multi-step";
export type Values = [
Form<{ name: string; surname: string; age: number }>,
Variables<{ nameSurname: string }>,
Return<{ nameSurname: string; age: number }>,
];
export const schema: Schema<Values> = [
{
form: {
values: () => ({
name: ["", []],
surname: ["", []],
age: [20, []],
}),
render: ({ values, onNext, onBack }) => (
<MultiStep onNext={onNext} onBack={onBack}>
<Step
key="main"
defaultValues={values}
resolver={zodResolver(
z.object({
name: z
.string()
.min(1, { message: "Required" })
.max(20, { message: "Must be at most 20 characters" }),
surname: z
.string()
.min(1, { message: "Required" })
.max(20, { message: "Must be at most 20 characters" }),
age: z
.number()
.min(18, { message: "Minimum of 18 years old" })
.max(99, { message: "Maximum of 99 years old" }),
}),
)}
>
<Layout
heading="Tell us about yourself"
description="We would want to know about you"
fields={[
<Row
key="nameSurname"
items={[
<TextField key="name" name="name" label="Name" />,
<TextField key="surname" name="surname" label="Surname" />,
]}
/>,
<NumberField key="age" name="age" label="Age" />,
]}
button={<NextButton>Next</NextButton>}
/>
</Step>
</MultiStep>
),
},
},
{
variables: ({ name, surname }) => ({
nameSurname: `${name} ${surname}`,
}),
},
{
return: ({ nameSurname, age }) => ({
nameSurname,
age,
}),
},
];
We need to use the Variables
type and define the types of the variables.
export type Values = [
// ...
Variables<{ nameSurname: string }>,
// ...
];
Then, in the schema we need to create an object with the following structure.
export const schema: Schema<Values> = [
// ...
{
variables: ({ name, surname }) => ({
nameSurname: `${name} ${surname}`,
}),
},
// ...
];
The variables
function takes the input values and returns the variables to be created.