How do file input fields work in react with tan stack form? #2205
Replies: 2 comments
-
|
File inputs are the one case where you don't bind const form = useForm({
defaultValues: { avatar: null as File | null },
})
<form.Field
name="avatar"
children={(field) => (
<input
type="file"
onChange={(e) => field.handleChange(e.target.files?.[0] ?? null)}
/>
)}
/>The bits that trip people up:
With shadcn's There's an older thread with the same pattern for the Angular adapter if you want another angle: #679 |
Beta Was this translation helpful? Give feedback.
-
|
There's genuinely no dedicated example for this in the docs today, so worth spelling out the full pattern. The one hard constraint (this is a browser thing, not a TanStack Form limitation): a file input's <form.Field name="avatar">
{(field) => (
<input
type="file"
accept="image/*"
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.files?.[0])}
/>
)}
</form.Field>For multiple files, The other thing this pattern runs into: clearing the field in code (on const [inputKey, setInputKey] = useState(0)
// ...
<input
key={inputKey}
type="file"
onChange={(e) => field.handleChange(e.target.files?.[0])}
/>
// wherever the reset happens:
form.reset()
setInputKey((k) => k + 1) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I'm currently trying to implement a form in react using shadcn/ui with tanstack form.
Can't really find docs for this use case. Any ideas?
Beta Was this translation helpful? Give feedback.
All reactions