TanStackT
TanStack14mo ago
15 replies
popular-magenta

Reusable Forms

Disclaimer: I think this came up already but I can't find it

I have an Address-Form where I collect the Street, Postalcode and City of the user.

I want to re-use the form for multiple purposes (Sign-Up, User-Profile, and Invoicing)


function AddressFormPart(
  // <-- what should I pass here?
) {
  return (
    <>
      <form.Field
        name="address.street"
        children={(field) => (
          <input
            id={field.name}
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
        )}
      />

      <form.Field
        name="address.city"
        children={(field) => (
          <input
            id={field.name}
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
        )}
      />

      <form.Field
        name="address.postalCode"
        children={(field) => (
          <input
            id={field.name}
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
        )}
      />
    </>
  )
}

function SignUp() {
  const form = useForm({
    defaultValues: {
      username: "",
      // more data to be collected…
      address: {
        street: "",
        city: "",
        postalCode: "",
      } 
    }
  })

  function handleSubmit() {}

  return (
    <form onSubmit={handleSubmit}>
      <form.Field
        name="username"
        children={(field) => (
          <input
            id={field.name}
            name={field.name}
            value={field.state.value}
            onBlur={field.handleBlur}
            onChange={(e) => field.handleChange(e.target.value)}
          />
        )}
      />
    </form>
  )
}
Was this page helpful?