TanStackT
TanStack9mo ago
13 replies
ordinary-sapphire

What's the recommended way to handle hidden fields?

I have a checkbox that, if checked, will make another text field appear. The zod validation will make use of .superRefine to require the text input value only if the checkbox is checked (its field as a value of true).

I noticed that depending on how I hide the text field, the meta (and the errors) may not be up-to-date.

Here some relevant code:
const invoiceEmailSameOrDifferent = useStore(form.store, (state) => state.values.invoiceEmailSameOrDifferent); // values are 'same' of 'different'

// radio buttons updating the value for invoiceEmailSameOrDifferent here

{invoiceEmailSameOrDifferent === 'different' && (
  <form.Field
    name="invoiceEmail"
    children={(field) => {
      return (
        <>
          <input
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
          <FieldInfo field={field} />
        </>
      );
    }}
  />
)}
<div hidden={invoiceEmailSameOrDifferent !== 'different'}>
  {<form.Field
    name="invoiceEmail"
    children={(field) => {
      return (
        <>
          <input
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
          <FieldInfo field={field} />
        </>
      );
    }}
  />}
</div>


In the first case I am not even mounting <form.Field /> while in the second case, I am using the hidden attribute of HTML to hide the input, but the TSF Field is always mounted/instatiated.

I noticed that sometimes the error is not displayed in the first case, meta.errors is empty. It kind of makes sense to me, so is hidden the recommended way to handle hidden fields in TSF?
Was this page helpful?