Basic concepts
Inputs
Learn how to pass values to be used inside the flow.
Inputs
As we move forward, an object with values is made available to each element. It contains the values from the form and variables elements encountered so far.
To provide additional values, we can use the inputs prop of the Formity component. To do this, the flow should be defined as follows.
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<{ language: string }>, s.Return<{ language: string }>];
inputs: {
languages: { label: string; value: string }[];
defaultLanguage: string;
};
params: Record<never, never>;
};
const flow: Flow<Schema> = [
{
form: {
fields: ({ defaultLanguage }) => ({
language: [defaultLanguage, []],
}),
render: ({ fields, values, onBack, onNext }) => (
<Form
key="language"
defaultValues={fields}
resolver={zodResolver(
z.object({
language: z.string(),
}),
)}
heading="What language do you speak the most?"
content={[
{
type: "select",
name: "language",
label: "Language",
placeholder: "Select an option",
options: values.languages,
},
]}
buttons={{
back: null,
next: "Next",
}}
onBack={onBack}
onNext={onNext}
/>
),
},
},
{
return: ({ language }) => ({ language }),
},
];
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}
inputs={{
languages: [
{ label: "English", value: "en" },
{ label: "Spanish", value: "es" },
{ label: "Catalan", value: "ca" },
],
defaultLanguage: "en",
}}
onReturn={onReturn}
/>
);
}