TanStackT
TanStack3mo ago
11 replies
awake-maroon

Generic array field with form composition

How can I create a generic array field that can be used across different forms that are created using
createFormHook
?

Eg. I want to create this array component:
import { withForm } from '../hooks/form';

const ArrayComponent = withForm({
  props: {
    name: '',
    children: null,
    className: '',
    id: '',
  },
  render: function Render({ form, name, children, className, id }) {
    return (
      <form.AppField name={name} mode='array'>
        {(field) =>
          field.state.value.map((_, index) => (
            <div className={className} key={index} id={id}>
              {children(field, index)}
            </div>
          ))
        }
      </form.AppField>
    );
  },
});

export default ArrayComponent;


And then use it in my forms like
<ArrayComponent name='people'>
  {(field, index) => (
    <div key={index}>
      <field.TextField
        name={`people[${index}].name`}
        label={i18n._(msg`Name`)}
      />
    </div>
  )}
</ArrayComponent>


But TS is telling me that 'field.state.value' is of type 'unknown'. I originally tried using useFormContext in ArrayComponent but after doing some searching I saw that wasn't recommended, so am trying the withForm pattern. Is there something I'm missing?
Was this page helpful?