T
TanStack9mo ago
genetic-orange

array with form composition

How can I use https://tanstack.com/form/latest/docs/framework/react/guides/arrays arrays with form composition. There are no examples of it and I cant type the useFormContext hook to make it work
Arrays | TanStack Form React Docs
TanStack Form supports arrays as values in a form, including sub-object values inside of an array. Basic Usage To use an array, you can use field.state.value on an array value: jsx function App() { co...
4 Replies
genetic-orange
genetic-orangeOP9mo ago
import { useFormContext } from "./use-form";

export const EntryField = () => {
const form = useFormContext();

return (
<form.Field name="people" mode="array">
{(field) => {
return (
<div>
{field.state.value.map((_, i) => {
return (
<form.Field key={i} name={`people[${i}].name`}>
{(subField) => {
return (
<div>
<label>
<div>Name for person {i}</div>
<input
value={subField.state.value}
onChange={(e) =>
subField.handleChange(e.target.value)
}
/>
</label>
</div>
);
}}
</form.Field>
);
})}
<button
onClick={() => field.pushValue({ name: "", age: 0 })}
type="button"
>
Add person
</button>
</div>
);
}}
</form.Field>
);
};
import { useFormContext } from "./use-form";

export const EntryField = () => {
const form = useFormContext();

return (
<form.Field name="people" mode="array">
{(field) => {
return (
<div>
{field.state.value.map((_, i) => {
return (
<form.Field key={i} name={`people[${i}].name`}>
{(subField) => {
return (
<div>
<label>
<div>Name for person {i}</div>
<input
value={subField.state.value}
onChange={(e) =>
subField.handleChange(e.target.value)
}
/>
</label>
</div>
);
}}
</form.Field>
);
})}
<button
onClick={() => field.pushValue({ name: "", age: 0 })}
type="button"
>
Add person
</button>
</div>
);
}}
</form.Field>
);
};
this is not working as field.state.value is of type unknown
exotic-emerald
exotic-emerald9mo ago
I don't think useFormContext() contains the full form type, which is why they created the withForm() hoc.
future-harlequin
future-harlequin9mo ago
useFormContext is really not meant to be used like this. I'd avoid that entirely and use either withForm. Or this pattern:
https://discord.com/channels/719702312431386674/1344358153759756328/1350936904568144043
exotic-emerald
exotic-emerald9mo ago
Holy crap that works!! I saw that comment a couple times but couldn't wrap my head around it. I think I finally understand how to make custom hooks in react.

Did you find this page helpful?