TanStackT
TanStack10mo ago
2 replies
hurt-tomato

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>,
  },
});


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>


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>


Thansk for all your help!
Was this page helpful?