Blog>
Snippets

Initializing a Form with TanStack Form

Demonstrate how to create a simple form using TanStack Form, including setting up initial form values and a basic submit handler.
import { useForm } from '@tanstack/react-form';
Importing the useForm hook from TanStack Form to manage the form state and handle submissions.
const defaultValues = { name: '', email: '' };
Setting up initial form values. Here, we are initializing a form with two fields: name and email, both starting as empty strings.
function MyForm() {
  const {
    Form,
    values,
    setValues
  } = useForm({
    defaultValues: defaultValues
  });

  const handleSubmit = async (values) => {
    // Handle form submission, values is an object with the form data
    console.log(values);
  };

  return (
    <Form
      onSubmit={handleSubmit}
    >
      <div>
        <label htmlFor="name">Name</label>
        <input
          id="name"
          name="name"
          value={values.name}
          onChange={e => setValues(current => ({ ...current, name: e.target.value }))}
        />
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          name="email"
          value={values.email}
          onChange={e => setValues(current => ({ ...current, email: e.target.value }))}
        />
      </div>
      <button type="submit">Submit</button>
    </Form>
  );
}
This function component demonstrates a basic form creation using TanStack Form, including initial values definition, a simple submission handler, and rendering of the form with two inputs for name and email.