Skip to content
Source
Sign inSign up
TanStack/form

docs(core): reusable fields & reusable field utility type #1084

Closedharry-whorlow(GitHub profile, opens in a new tab)wants to merge 6 commits intomain fromrefs/pull/1084/headopened

A continue on from #636, this PR introduces docs for reusable components/fields as well as introduces a Ts utility type for inferring valid field names, for the relevant component.

Much like my last PR this is something I was trying to do for a work project, but not having any docs or examples hindered the process, so I figured I'd give it a go.


Guidance wanted:

Specifically with this line onChange={(e) => handleChange(e.target.value as any)} (line 28 in reusable-fields) I can't stand the casting of any, however I can figure a way for Ts to infer this value. Any suggestions is greatly appreciated!


Sandbox

I have a code sandbox for playing around with this here, you'll see theres a folder called solutions that has two files:

  • one.tsx works and is a refined version of all my test components
  • two.tsx is another version that I haven't quite got working but in terms of user Ux I think is an improvement.

The rest of the files can be ignored but if you want to see how I got here they kind of explain my reasoning.

    1. View your CI Pipeline Execution ↗ for commit f0df80464039a65d9719353fd10699fbb23729d6.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...❌ Failed2m 18sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded29sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-01-06 07:54:10 UTC

    2. Open in Stackblitz

      More templates

      @tanstack/angular-form

      npm i https://pkg.pr.new/@tanstack/angular-form@1084

      @tanstack/form-core

      npm i https://pkg.pr.new/@tanstack/form-core@1084

      @tanstack/react-form

      npm i https://pkg.pr.new/@tanstack/react-form@1084

      @tanstack/lit-form

      npm i https://pkg.pr.new/@tanstack/lit-form@1084

      @tanstack/solid-form

      npm i https://pkg.pr.new/@tanstack/solid-form@1084

      @tanstack/valibot-form-adapter

      npm i https://pkg.pr.new/@tanstack/valibot-form-adapter@1084

      @tanstack/vue-form

      npm i https://pkg.pr.new/@tanstack/vue-form@1084

      @tanstack/yup-form-adapter

      npm i https://pkg.pr.new/@tanstack/yup-form-adapter@1084

      @tanstack/zod-form-adapter

      npm i https://pkg.pr.new/@tanstack/zod-form-adapter@1084

      commit: f0df804

    3. Codecov Report

      All modified and coverable lines are covered by tests :white_check_mark:

      Project coverage is 86.75%. Comparing base (91eb9ab) to head (f283513). Report is 4 commits behind head on main.

      Additional details and impacted files
      @@            Coverage Diff             @@
      ##             main    #1084      +/-   ##
      ==========================================
      + Coverage   86.61%   86.75%   +0.13%     
      ==========================================
        Files          29       29              
        Lines        1158     1155       -3     
        Branches      301      298       -3     
      ==========================================
      - Hits         1003     1002       -1     
      + Misses        142      140       -2     
        Partials       13       13              

      :umbrella: View full report in Codecov by Sentry. :loudspeaker: Have feedback on the report? Share it here.

    4. OutdatedResolvedby harry-whorlow(GitHub profile, opens in a new tab)
    5. Sorry for the push forces... was looking at the incorrect section of code and wondering why it wasn't changing. Friday’s for you 🙃

    6. packages/react-form/src/types.ts line 35
      @@ -28,3 +28,8 @@
      2828 > & {
      2929 mode?: 'value' | 'array'
      3030 }
      31+
      32+/**
      33+ * The return type use useForm with pre-populated generics
      34+ */
      35+export type UseFormReturnType<TForm, TFormValidator> = TFormValidator extends

      I would love to get rid of the TFormValidator slot, since TFormValidator is just Validator<TForm, unknown> | undefined. But so far my efforts have been fruitless.

    7. docs/framework/react/guides/reusable-fields.md line 27
      @@ -0,0 +7,21 @@
      7+
      8+## Basic Usage
      9+
      10+To create a reusable fields, you can do the following.
      11+
      12+```tsx
      13+import { InferValidFormKeys, UseFormReturnType } from '@tanstack/react-form';
      14+
      15+export default function GenericTextField<
      16+ TForm,
      17+ TFormValidator
      18+>({ name, form }: {
      19+ name: InferValidFormKeys<TForm, string>;
      20+ form: UseFormReturnType<TForm, TFormValidator>,
      21+> }): JSX.Element {
      22+ return (
      23+ <form.Field name={name}>
      24+ {({ handleChange, handleBlur, state }) => (
      25+ <input
      26+ value={state.value}
      27+ onChange={(e) => handleChange(e.target.value as any)}

      Another improvement would be to get Ts to infer the handleChange value so the update is type safe.

    8. @Talent30 yeah, I was talking with crutchcorn about this on Friday and he made me aware of it. He said to leave it open for now, and he'll link it to his issue. Though, I'm not sure how useful it'll be, as after reading though the linked Pr, they've run into all the same problems I have. 🙃

    9. wonder if it'd be possible to do something like form.Field as a way to provide your components.

         function useMyForm(args) {
             const form = useForm(args);
             return {
                ...form
               TextField: function ({ name }) {
                    return (
                        <form.Field name={name}>
                              {({ handleChange, handleBlur, state }) => (
                                <input
                                  value={state.value}
                                  onChange={(e) => handleChange(e.target.value as any)}
                                  onBlur={handleBlur}
                                />
                              )}
                        </form.Field>
                    );
                }
             }
         }

      then to use it it's just like form.Field

        const form = useMyForm(args);
      
        <form.TextField name="blah" />
      ...
    10. @bzbetty I think the issue with the proposed solution is that if the form is apart of the component then your re-instantiating the form on every component. So instead of having one form controlling the fields, you will have multiple standalone forms controlling a single field then passing the data back to whatever the args is.

      After seeing the proposed solutions in #825, and after banging my head against the keyboard for a couple weeks, I think its probably the best way to go. Though I will admit if you could get the form typing your solution would probably address the internal typing issues I ran into in my attempt.

    11. Closing in favor of an alternative API we're proposing here: #1179

Sign in to join this conversation.