TanStackT
TanStack•13mo ago•
17 replies
primary-violet

Generic Form Components

I figured Id drag my post from the general channel, over to here as I've hit a wall with the Ts that I'm working on.

Here's my code sandbox https://codesandbox.io/p/sandbox/yv7zmh demo, and the original post that i made in general https://discord.com/channels/719702312431386674/1100437019857014895/1318637134667583508

Basically, I wanted to carry on from the discussion on this issue (https://github.com/TanStack/form/discussions/636) to open a PR with some documentation on reusable components. It's something that I'm trying to get working at work but I'm having massive Ts performance hits, and so I think it might be a good time to reach out to someone more familiar with the matter.


import TextField from "@mui/material/TextField";

import {
  DeepKeys,
  ReactFormExtendedApi,
  Validator,
} from "@tanstack/react-form";
import { DeepValue } from "@tanstack/react-form";

type IsDeepValueString<T, K extends DeepKeys<T>> = DeepValue<
  T,
  K
> extends string
  ? K
  : never;
type StringDeepKeys<T> = {
  [P in DeepKeys<T>]: IsDeepValueString<T, P>;
}[DeepKeys<T>];

export default function GenericTextField<
  TFormData,
  TFormValidator extends Validator<TFormData, unknown> | undefined,
  Form extends ReactFormExtendedApi<TFormData, TFormValidator>,
  // Name extends DeepKeys<TFormData>,
  Name extends DeepKeys<TFormData> & StringDeepKeys<Form>
>({
  name,
  label,
  form: { Field },
}: {
  name: Name;
  label?: string;
  form: Form;
}): JSX.Element {
  return (
    <Field name={name}>
      {({ handleChange, handleBlur, state }) => (
        <TextField
          label={label}
          name={String(name)}
          onChange={(e) => {
            handleChange(e.target.value);
          }}
          onBlur={handleBlur}
          value={state.value}
        />
      )}
    </Field>
  );
}


Any help is massively appreciated, or even a repo to look at for inspiration would be great.

Thanks in advance!! 🤟
GitHub
Hey! Love tanstack form and recently switched from another library. A question about the correct usage of generics for reuseable fields The code below results in a type error on the name prop. How ...
Generics for useForm for custom components for fields Ā· TanStack fo...
Was this page helpful?