Blog>
Snippets

Basic Form Setup

Demonstrates initializing a simple form with input fields using the TanStack Form library and handling form submission.
import React from 'react';
import { useForm } from '@tanstack/react-form';

export default function BasicForm() {
  const form = useForm({
    defaultValues: React.useMemo(() => ({
      name: '',
      email: '',
    }), []),
    onSubmit: async (values) => {
      console.log(values);
      // Here you would typically handle form submission, such as sending data to a server
    },
  });

  return (
    <form onSubmit={form.handleSubmit}>
      <input
        type="text"
        {...form.fields.name.getInputProps()}
        placeholder="Name"
      />
      <input
        type="email"
        {...form.fields.email.getInputProps()}
        placeholder="Email"
      />
      <button type="submit">Submit</button>
    </form>
  );
}
This code snippet demonstrates a basic form setup using TanStack Form library. It includes two input fields for 'name' and 'email'. The useForm hook is used to create form logic, including default values and a submission handler. The 'getInputProps' method is used to bind input fields to the form state, facilitating built-in handleChange and other events automatically. Upon form submission, a simple log of form values is shown as a placeholder for actual submission logic.