Basic concepts
Params
Learn how to pass values that can be used when rendering each form.
Params
The params
prop of the Formity
component allows us to pass values meant to be used when rendering each form. Unlike the inputs
prop, these values are exclusively for rendering purposes, and any changes to them will dynamically update the form.
To pass these values, 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 { Step, Layout, MultiSelect, NextButton } from "./components";
import { MultiStep } from "./multi-step";
export type Values = [
Form<{ languages: string[] }>,
Return<{ languages: string[] }>,
];
export type Inputs = {
options: { label: string; value: string }[];
defaultOptions: string[];
};
export type Params = {
heading: string;
description: string;
};
export const schema: Schema<Values, Inputs, Params> = [
{
form: {
values: ({ defaultOptions }) => ({
languages: [defaultOptions, []],
}),
render: ({ inputs, values, params, onNext, onBack }) => (
<MultiStep onNext={onNext} onBack={onBack}>
<Step
key="languages"
defaultValues={values}
resolver={zodResolver(
z.object({
languages: z.array(z.string()),
}),
)}
>
<Layout
heading={params.heading}
description={params.description}
fields={[
<MultiSelect
key="languages"
name="languages"
label="Languages"
options={inputs.options}
direction="y"
/>,
]}
button={<NextButton>Next</NextButton>}
/>
</Step>
</MultiStep>
),
},
},
{
return: ({ languages }) => ({
languages,
}),
},
];
We pass the Params
type to the Schema
to specify the types of the values.
We can now provide the values using the params
prop of the Formity
component.
import { useCallback, useState } from "react";
import { Formity, OnReturn, ReturnOutput } from "@formity/react";
import { Data } from "./components";
import { schema, Values, Inputs, Params } from "./schema";
export default function App() {
const [values, setValues] = useState<ReturnOutput<Values> | null>(null);
const onReturn = useCallback<OnReturn<Values>>((values) => {
setValues(values);
}, []);
if (values) {
return <Data data={values} onStart={() => setValues(null)} />;
}
return (
<Formity<Values, Inputs, Params>
schema={schema}
inputs={{
options: [
{ value: "javascript", label: "JavaScript" },
{ value: "python", label: "Python" },
{ value: "go", label: "Go" },
],
defaultOptions: ["javascript"],
}}
params={{
heading: "What are your favourite programming languages?",
description: "We would like to know the ones you like the most",
}}
onReturn={onReturn}
/>
);
}