Blog>
Snippets

Integrating TanStack Form with TypeScript for Enhanced Type Safety

Demonstrate setting up TanStack Form in a TypeScript project to leverage type safety features, reducing bugs and improving developer experience.
interface UserFormData {
  name: string;
  email: string;
  age?: number;
}
Defines the TypeScript interface for our form, specifying the structure and types of the data we expect to handle. The age field is optional.
import { useForm, SubmitHandler } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
Imports the necessary modules from 'react-hook-form' and YUP for schema validation.
const schema = yup.object({
  name: yup.string().required(),
  email: yup.string().email().required(),
  age: yup.number().positive().integer().optional()
}).required();
Defines the validation schema using YUP, ensuring our form data adheres to the defined structure and types.
const FormComponent: React.FC = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<UserFormData>({ resolver: yupResolver(schema) });

  const onSubmit: SubmitHandler<UserFormData> = data => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} />
      {errors.name && <p>{errors.name.message}</p>}
      <input {...register('email')} />
      {errors.email && <p>{errors.email.message}</p>}
      <input type="number" {...register('age')} />
      {errors.age && <p>{errors.age.message}</p>}
      <button type="submit">Submit</button>
    </form>
  );
};
Sets up the form component using TanStack Form (previously react-hook-form) with YUP integration for schema validation. Utilizes the 'register' function for input fields to connect them with the useForm hook, adhering to the UserFormData interface structure.