Form flow
Return
Learn how the return element is used in the flow.
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 { 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.Return<{ fullName: string; age: number }>,
];
inputs: Record<never, never>;
params: Record<never, never>;
};
const flow: Flow<Schema> = [
{
form: {
fields: () => ({
name: ["", []],
surname: ["", []],
age: [20, []],
}),
render: ({ fields, onBack, onNext }) => (
<Form
key="yourself"
defaultValues={fields}
resolver={zodResolver(
z.object({
name: z.string().nonempty("Required"),
surname: z.string().nonempty("Required"),
age: z.number().min(18, "Min. 18").max(99, "Max. 99"),
}),
)}
heading="Tell us about yourself"
content={[
{
type: "columns",
columns: [
{
type: "input",
name: "name",
label: "Name",
placeholder: "Your name",
},
{
type: "input",
name: "surname",
label: "Surname",
placeholder: "Your surname",
},
],
},
{
type: "number",
name: "age",
label: "Age",
placeholder: "Your age",
},
]}
buttons={{
back: null,
next: "Next",
}}
onBack={onBack}
onNext={onNext}
/>
),
},
},
{
return: ({ name, surname, age }) => ({
fullName: `${name} ${surname}`,
age,
}),
},
];
export default function App() {
const [output, setOutput] = useState<ReturnOutput<Schema> | null>(null);
const onReturn = useCallback<OnReturn<Schema>>((output) => {
setOutput(output);
}, []);
if (output) {
return <Output output={output} onStart={() => setOutput(null)} />;
}
return <Formity<Schema> flow={flow} onReturn={onReturn} />;
}
We need to use the s.Return type and define the types of the values to be returned.
type Schema = {
// ...
struct: [
// ...
s.Return<{ fullName: string; age: number }>,
];
// ...
};
Then, in the flow we need to create an object with the following structure.
const flow: Flow<Schema> = [
// ...
{
return: ({ name, surname, age }) => ({
fullName: `${name} ${surname}`,
age,
}),
},
];
The return function takes the input values and returns the values to be returned.