Custom ConditionalField
I am trying to simplify the way i handle conditional fields. For example i have a
If
role
field which can be set to either "User" | "Admin"
.If
"Admin"
is set a new required field reason
should appear.
I have seen approaches where users add an onChange listener to the field role
and it works fine. However this is a simple usecase. My actual use case is a big multi step form where the field might be rendered somewhere completely different.
I generally don't like separating logic (In this case the listener) and rendering (of the field in some other subform later).
I endeavered to replicate the listener approach with the help of form.Subscribe
and came up with a simple custom form.ConditionalField
:
As stated in above example i loose typesafety of the condition
function and name
prop.
How can i correctly type it?4 Replies
genetic-orangeOP•6mo ago
In a perfect world i would also wrap form.AppField and pass the name property through correctly aswell.
however the
form
object returned by useFormContext
doesn't have the AppField
componentquickest-silver•6mo ago
can you put tsx so your code example gets more readable?
genetic-orangeOP•6mo ago
also added a stackblitz:
https://stackblitz.com/edit/vitejs-vite-vqrqfen2?file=src%2Fcomponents%2Fselect-field.tsx
Clemens Pflaum
StackBlitz
Tanstack Form custom conditional field - StackBlitz
Next generation frontend tooling. It's fast!
genetic-orangeOP•6mo ago
seems like for fieldComponents i can use the generic of
useFieldContext<string>()
to manually bridge this type gap.
But formComponents/useFormContext
has no way to provide a generic type.