#Typesafety in FormAPI and FieldAPI for Shadcn Form Components

1 messages · Page 1 of 1 (latest)

somber jungle
#

Hi @cerulean coral

Just following up from our convo — I’m the one working on the TanStack Forms + shadcn/ui integration. I’m mainly stuck with getting things fully type-safe, especially around FormAPI and FieldAPI.

example code:

const Form = React.forwardRef<
  HTMLFormElement, 
  {
    form: FormApi<any, any, any, any, any, any, any, any, any, any>,
    children: React.ReactNode
  } & React.HTMLAttributes<HTMLFormElement>
>(({ form, children, ...props }, ref) => {
  return (
    <form
      ref={ref}
      onSubmit={(e) => {
        e.preventDefault()
        e.stopPropagation()
        void form.handleSubmit()
      }}
      {...props}
    >
      {children}
    </form>
  )
})
Form.displayName = "Form"

Github URL: https://github.com/kulterryan/shadcn-tanstack-form/blob/main/src/components/ui/tanstack-form.tsx

GitHub

Contribute to kulterryan/shadcn-tanstack-form development by creating an account on GitHub.

long shard
somber jungle
#

Ok let me check that.

somber jungle
#

I tried, but not able to understand the docs properly.

long shard
somber jungle
long shard
# somber jungle I'm trying to make the whole forms component composable like shadcn has done wit...

you're likely used to a system like image 1.

Summarized, Tanstack Form works with the system in the second image.

If you want it to be as composable as possible, you'd provide the user with the field and form components. They may then decide which ones to pass onto createFormHook() and which ones to discard. You will also want to generate a fieldContext and formContext for them to use in the hook, as you'll use the respective useFieldContext()| useFormContext() hooks in your shadcn components

#

so the usage would look less like:

<TextInput field={field}/>
<Feedback field={field}/>

And more like

<form.AppField name="path.to.field">
  {field => <>
    <field.TextInput/>
    <field.Feedback/>
  </>}
</form.AppField>
#

That‘s still assuming you‘re planning to follow these general guidelines. It‘s possible to create a structure like the former code snippet, with some more effort.

marsh root