T
TanStack6mo ago
foreign-sapphire

Type-Safe name prefix

I’m creating a dynamic form, that gets assembled based on an API response. It consists of a couple of groups of fields. Each group renders many dynamic fields. Dynamic field takes care of rendering an appropriate input based on some value in payload. Now what I need is a type-safe way to prefix the field name, so that I can take care of connecting the dynamic field inputs to the form. I mention prefix, because my Dynamic Field shouldn’t know about an arbitrary grouping it’s rendered in.
type DynamicField = {
name: string;
value: unknown;
fieldType: 'address' | 'number' | 'whatever';
// other properties
};

const options = formOptions({
defaultValues: {
group1: [] as Array<DynamicField>,
group2: [] as Array<DynamicField>,
group3: [] as Array<DynamicField>,
group4: [] as Array<DynamicField>,
},
});
type DynamicField = {
name: string;
value: unknown;
fieldType: 'address' | 'number' | 'whatever';
// other properties
};

const options = formOptions({
defaultValues: {
group1: [] as Array<DynamicField>,
group2: [] as Array<DynamicField>,
group3: [] as Array<DynamicField>,
group4: [] as Array<DynamicField>,
},
});
When I’m rendering it, I need to provide the specific path to the name:
<form.Field name="group1" mode="array">
{(field) => (
<div>
{field.state.value.map((_, i) => (
<form.Field key={i} name={`group1[${i}].name`}>
{(subField) => {
return <div>...</div>;
}}
</form.Field>
))}
</div>
)}
</form.Field>
<form.Field name="group1" mode="array">
{(field) => (
<div>
{field.state.value.map((_, i) => (
<form.Field key={i} name={`group1[${i}].name`}>
{(subField) => {
return <div>...</div>;
}}
</form.Field>
))}
</div>
)}
</form.Field>
I’m looking for something like this, but typesafe, so I could take care of rendering individual fields in Dynamic Input, without needing to know what context (group) I’m rendering it in:
<form.Field name="group1" mode="array">
{(field) => (
<div>
{field.state.value.map((_, i) => (
<DynamicField prefix={`group1[${i}].`} />
))}
</div>
)}
</form.Field>
<form.Field name="group1" mode="array">
{(field) => (
<div>
{field.state.value.map((_, i) => (
<DynamicField prefix={`group1[${i}].`} />
))}
</div>
)}
</form.Field>
Thansk for all your help!
2 Replies
foreign-sapphire
foreign-sapphireOP6mo ago
I think if I create a union of possible group names and use it inside the key it should work
foreign-sapphire
foreign-sapphireOP6mo ago
Oh I see it’s already been discussed & suggested by @crutchcorn
GitHub
Compose forms with nested form structure · TanStack form · Discus...
The new createFormHook looks great but it appears that it only works when there's a shared data structure between the child and parent forms. The use case where this applies is when you have a ...

Did you find this page helpful?