Form schema
Return
Learn how the Return element is used in the schema.
Usage
The Return element is used to define what the multi-step form returns. This element will trigger the onReturn
callback function of the Formity
component.
To understand how it is used let's look at this example:
import type { Schema, Form, Return } from "@formity/react";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { FormView, FormLayout, TextField, Next } from "./components";
import { Controller } from "./controller";
export type Values = [
Form<{ name: string; surname: string }>,
Return<{ fullName: string }>,
];
export const schema: Schema<Values> = [
{
form: {
values: () => ({
name: ["", []],
surname: ["", []],
}),
render: ({ values, onNext, onBack, getState, setState }) => (
<Controller
step="name-surname"
onNext={onNext}
onBack={onBack}
getState={getState}
setState={setState}
>
<FormView
defaultValues={values}
resolver={zodResolver(
z.object({
name: z.string(),
surname: z.string(),
}),
)}
>
<FormLayout
heading="What is your name?"
description="We would like to know what is your name"
fields={[
<TextField key="name" name="name" label="Name" />,
<TextField key="surname" name="surname" label="Surname" />,
]}
button={<Next>Next</Next>}
/>
</FormView>
</Controller>
),
},
},
{
return: ({ name, surname }) => ({
fullName: `${name} ${surname}`,
}),
},
];
We need to use the Return
type and define the types of the values to be returned:
export type Values = [
// ...
Return<{ fullName: string }>,
];
Then, in the schema we need to create an object with the following structure:
export const schema: Schema<Values> = [
// ...
{
return: ({ name, surname }) => ({
fullName: `${name} ${surname}`,
}),
},
];
The return
function takes the values generated in previous steps and returns the values to be returned.