Basic concepts

Inputs

Learn how to pass values to be used inside the schema.


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 schema should be defined as follows.

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 const schema: Schema<Values, Inputs> = [
  {
    form: {
      values: ({ defaultOptions }) => ({
        languages: [defaultOptions, []],
      }),
      render: ({ inputs, values, onNext, onBack }) => (
        <MultiStep onNext={onNext} onBack={onBack}>
          <Step
            key="languages"
            defaultValues={values}
            resolver={zodResolver(
              z.object({
                languages: z.array(z.string()),
              }),
            )}
          >
            <Layout
              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={<NextButton>Next</NextButton>}
            />
          </Step>
        </MultiStep>
      ),
    },
  },
  {
    return: ({ languages }) => ({
      languages,
    }),
  },
];

We pass the Inputs type to Schema to specify the types of the values.

We can now provide the values using the inputs 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 } 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>
      schema={schema}
      inputs={{
        options: [
          { value: "javascript", label: "JavaScript" },
          { value: "python", label: "Python" },
          { value: "go", label: "Go" },
        ],
        defaultOptions: ["javascript"],
      }}
      onReturn={onReturn}
    />
  );
}