Skip to main content

Conditional Rendering with FormSwitch

FormSwitch renders one FormCase for the current discriminator value. Use createFormCase with a discriminated union so that each case receives the narrowed form type for its branch.

Typed discriminated-union form​

import { FormProvider, useForm } from "el-form-react-hooks";
import { createFormCase, FormSwitch } from "el-form-react-components";

type Payment =
| { method: "card"; cardNumber: string }
| { method: "cash"; receiptEmail: string };

const PaymentCase = createFormCase<Payment, "method">();

export function PaymentFields() {
const form = useForm<Payment>({
defaultValues: { method: "card", cardNumber: "" },
});

return (
<FormProvider form={form}>
<FormSwitch<Payment> field="method">
<PaymentCase value="card">
{cardForm => (
<input {...cardForm.register("cardNumber")} aria-label="Card number" />
)}
</PaymentCase>
<PaymentCase value="cash">
{cashForm => (
<input {...cashForm.register("receiptEmail")} aria-label="Receipt email" />
)}
</PaymentCase>
</FormSwitch>
</FormProvider>
);
}

field is required for this typed API. It anchors the discriminator path and lets createFormCase reject values that are not members of that field's union. The cardForm callback only exposes card fields; the cash callback only exposes cash fields.

Derive the active case with select​

Use select when the active case depends on more than one form value. The selector receives current values and returns the case value to render. It is subscribed by its selected primitive, so an update that leaves the selector's result unchanged does not re-render the switch.

type Shipping =
| { country: "us"; hasExpressAccess: boolean; note: string; stateCode: string }
| { country: "es"; hasExpressAccess: boolean; note: string; province: string };

const ShippingCase = createFormCase<Shipping, "country">();

const visibleCountry = (values: Partial<Shipping>) =>
values.hasExpressAccess ? values.country : undefined;

<FormSwitch<Shipping> field="country" select={visibleCountry}>
<ShippingCase value="us">
{form => <input {...form.register("stateCode")} aria-label="State code" />}
</ShippingCase>
<ShippingCase value="es">
{form => <input {...form.register("province")} aria-label="Province" />}
</ShippingCase>
</FormSwitch>;

Keep the selector stable when practical (for example, define it outside the rendering component or use useCallback). A new selector prop is used on the next render. Returning null or undefined renders no case. false and 0 are valid case values and still match their cases.

The example hides the country-specific input until express shipping is available. The form still submits its stored country. For a selector that can display a different country, use the whole output type in your submit callback: createFormCase<Shipping, "country", Shipping>(). Use select with hand-written FormCase children.

Schema-driven cases​

For a Zod discriminated-union schema, use schema and SchemaFormCase. SchemaFormCase validates the discriminator value against the schema input.

import { z } from "zod";
import { FormSwitch, SchemaFormCase } from "el-form-react-components";

const paymentSchema = z.discriminatedUnion("method", [
z.object({ method: z.literal("card"), cardNumber: z.string() }),
z.object({ method: z.literal("cash"), receiptEmail: z.string().email() }),
]);

<FormSwitch schema={paymentSchema}>
<SchemaFormCase<typeof paymentSchema, "method", "card">
discriminatorField="method"
value="card"
>
{form => <input {...form.register("cardNumber")} />}
</SchemaFormCase>
<SchemaFormCase<typeof paymentSchema, "method", "cash">
discriminatorField="method"
value="cash"
>
{form => <input {...form.register("receiptEmail")} />}
</SchemaFormCase>
</FormSwitch>;

When schema is supplied, FormSwitch reads the schema discriminator. Passing field is optional, and a different field produces a development warning.

Generated branches​

unionOptions, discriminatorValue, and renderCase support generated AutoForm branches. They are not a case-list validation API. In particular, FormSwitch does not accept a values tuple and does not perform duplicate or exhaustiveness checks for case children. Keep exactly one direct FormCase per value; the anchored runtime warns about direct duplicate values.

Legacy API​

The legacy on and form props still work for existing applications, but do not provide branch narrowing. Prefer field and createFormCase for new forms.