T
TanStack14mo ago
flat-fuchsia

Conditional disable

how can I disable a form fields based on the value selected in another form field?
5 Replies
flat-fuchsia
flat-fuchsiaOP14mo ago
I already checked it out but didn't quite understand how to set the disable, I tried something like this:
disabled={field.form.getFieldValue("job") === "Teacher"}
disabled={field.form.getFieldValue("job") === "Teacher"}
but it doesn't look reactive
genetic-orange
genetic-orange14mo ago
@Ladvace I guess this is more for validation logic. I did figure it out. Use form.Subscribe For example I did implement this on the simple example:
<form.Subscribe
selector={(state) => [state.values.firstName]}
children={([firstName]) => (
<form.Field
name="lastName"
children={(field) => (
<>
<label htmlFor={field.name}>Last Name:</label>
<input
id={field.name}
name={field.name}
disabled={firstName === "Bob"}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
</>
)}
/>)}
/>
<form.Subscribe
selector={(state) => [state.values.firstName]}
children={([firstName]) => (
<form.Field
name="lastName"
children={(field) => (
<>
<label htmlFor={field.name}>Last Name:</label>
<input
id={field.name}
name={field.name}
disabled={firstName === "Bob"}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
</>
)}
/>)}
/>
So, it is similar to how we would get the canSubmit and isSubmitting for the Button but instead we select the state.value we need.
flat-fuchsia
flat-fuchsiaOP14mo ago
I see, thanks, i'm gonna give it a look
genetic-orange
genetic-orange14mo ago
Reactivity can be mainly achieved in two ways, with form.useStore or form.Subscribe (docs) Susbscribe works fine but in your case I'd go with useStore to avoid that extra level of nesting
const myField = form.useStore((state) => state.values.myField)
//...
<form.Field
...
<input
disabled={myField.length < 2}
const myField = form.useStore((state) => state.values.myField)
//...
<form.Field
...
<input
disabled={myField.length < 2}
Basic Concepts and Terminology | TanStack Form React Docs
This page introduces the basic concepts and terminology used in the @tanstack/react-form library. Familiarizing yourself with these concepts will help you better understand and work with the library. Form Options

Did you find this page helpful?