Blog>
Snippets

Setting Up a Typed Form Using TanStack Form and TypeScript

Demonstrate how to initialize a form with TanStack Form in a TypeScript environment, defining form inputs with specific types.
import { useForm } from 'tanstack-form';

interface FormValues {
  name: string;
  age: number;
}

export function MyForm() {
  const { register, handleSubmit } = useForm<FormValues>({ defaultValues: { name: '', age: 0 } });

  const onSubmit = (data: FormValues) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} placeholder='Name' />
      <input type='number' {...register('age')} placeholder='Age' />
      <button type='submit'>Submit</button>
    </form>
  );
}
This code demonstrates how to initialize a form with TanStack Form in a TypeScript environment. It utilizes the useForm hook to create a form for capturing a user's name and age. The FormValues interface explicitly defines the types of form fields, ensuring type safety. The register function returned from useForm is used to connect the input fields to the form state. Finally, the form data is logged to the console upon submission.