Fieldsets and scopes
Type a component that renders one part of a form, and use it on every form with that part.
One component renders both addresses below. It takes a handle, and its names are relative to it.
Typing the handle
A component that renders part of a form takes a handle prop. To type it,
make a fieldset from the part’s schema and use HandleOf:
import type { HandleOf } from "@lunarhue/forms-react";
const AddressFieldset = forms.fieldset(Address);
function AddressFields({ field }: { field: HandleOf<typeof AddressFieldset> }) {
const scope = AddressFieldset.scope(field);
return (
<fieldset>
<scope.TextField name="street" label="Street" />
<scope.TextField name="city" label="City" />
</fieldset>
);
}
<AddressFields field={form.root.at("shipping")} />;Scopes
scope(handle) returns the same members a form has, Field, Items and
your registered components, with names relative to the handle. It is a cached
lookup, not a hook, so call it anywhere.
The fieldset’s schema only types the shape. The form’s own schema does the
validating. Without a schema, write the type: forms.fieldset<Address>().
Which handles fit
A handle fits when its value has exactly the shape: an array row, or a field
of another form from the same createForms. A handle of an object with more
keys doesn’t. The component could replace the whole value and drop the keys
it doesn’t know, so handles are strict in their value type. A handle of a
form with more plugins still fits one that asks for fewer.
Generic fieldsets
To take objects with more keys, make the component generic in the value and
pass it as the second argument of HandleOf:
function AddressFields<A extends Address>({ field }: { field: HandleOf<typeof AddressFieldset, A> }) {
const scope = AddressFieldset.scope(field);
return (
<fieldset>
<scope.TextField name="street" label="Street" />
<scope.TextField handle={field.at("city")} label="City" />
</fieldset>
);
}
// `office` has a `phone` too.
<AddressFields field={form.root.at("office")} />;A child that Address names, such as field.at("city"), reads as its type
in Address, so it fits a FieldApi<string> component. A child that is an
object itself stays generic and needs a generic component of its own. A
merge write such as field.setValue({ city: "Oslo" }) doesn’t type-check on
a generic handle. Write the child instead: field.at("city").setValue("Oslo").
useInputProps reads the value type from the handle’s own type, so type the
child first: const city: FieldHandle<string> = field.at("city").
Last updated