Basic concepts
Inputs
Learn how to pass additional values to be used inside the schema.
Inputs
We can pass additional values using the inputs
prop of the Formity
component. For that, we first need to define the schema the following way:
import type { Schema, Form, Return } from "@formity/react";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { FormView, FormLayout, MultiSelect, Next } from "./components";
import { Controller } from "./controller";
export type Values = [
Form<{ languages: string[] }>,
Return<{ languages: string[] }>,
];
export type Inputs = {
options: { label: string; value: string }[];
defaultOptions: string[];
};
export const schema: Schema<Values, Inputs> = [
{
form: {
values: ({ defaultOptions }) => ({
languages: [defaultOptions, []],
}),
render: ({ inputs, values, onNext, onBack, getFlow, setFlow }) => (
<Controller
step="languages"
onNext={onNext}
onBack={onBack}
getFlow={getFlow}
setFlow={setFlow}
>
<FormView
key="languages"
defaultValues={values}
resolver={zodResolver(
z.object({
languages: z.array(z.string()),
}),
)}
>
<FormLayout
heading="What are your favourite programming languages?"
description="We would like to know the ones you like the most"
fields={[
<MultiSelect
key="languages"
name="languages"
label="Languages"
options={inputs.options}
direction="y"
/>,
]}
button={<Next>Next</Next>}
/>
</FormView>
</Controller>
),
},
},
{
return: ({ languages }) => ({
languages,
}),
},
];
As you can see, we have passed the Inputs
type to the Schema
type to define the additional values available within the schema. These values can be accessed just like those generated by the multi-step form itself.
We can now provide the values using the inputs
prop of the Formity
component:
import { useCallback, useState } from "react";
import { Formity, OnReturn, ReturnValues } from "@formity/react";
import { Data } from "./components";
import { schema, Values, Inputs } from "./schema";
export default function App() {
const [values, setValues] = useState<ReturnValues<Values> | null>(null);
const onReturn = useCallback<OnReturn<Values>>((values) => {
setValues(values);
}, []);
if (values) {
return <Data data={values} onStart={() => setValues(null)} />;
}
return (
<Formity<Values, Inputs>
schema={schema}
inputs={{
options: [
{ value: "javascript", label: "JavaScript" },
{ value: "python", label: "Python" },
{ value: "go", label: "Go" },
],
defaultOptions: ["javascript"],
}}
onReturn={onReturn}
/>
);
}