Blog>
Snippets

Basic Form Setup with TanStack Form

Demonstrate setting up a simple form with TanStack Form, including basic input fields and form submission.
import { useForm, FormProvider, Field } from '@tanstack/react-form';
Import the necessary functions and components from the TanStack Form library.
function BasicForm() {
  const form = useForm({
    defaultValues: { firstName: '', lastName: '' },
    onSubmit: async (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });

  return (
    <FormProvider form={form}>
      <form onSubmit={form.handleSubmit}>
        <Field
          name='firstName'
          component='input'
          placeholder='First Name'
        />
        <Field
          name='lastName'
          component='input'
          placeholder='Last Name'
        />
        <button type='submit'>Submit</button>
      </form>
    </FormProvider>
  );
}
Create a functional component using useForm hook to set up a form with first name and last name fields. The FormProvider component wraps the form to bind it with the useForm instance. Field components are used to render input fields. onSubmit triggers an alert with form values.