Blog>
Snippets

Initializing TanStack Form in a React Component

Demonstrate initializing TanStack Form within a React functional component, including setting up initial form values.
import React from 'react';
import { useForm } from '@tanstack/react-form';
Imports React and useForm hook from TanStack React Form library.
function MyFormComponent() {
  const form = useForm({
    defaultValues: {
      firstName: '',
      lastName: ''
    }
  });
Defines a functional component and initializes the form with useForm hook including default values for firstName and lastName.
return (
    <form onSubmit={form.handleSubmit((values) => {
      console.log(values);
    })}>
      <input {...form.register('firstName')} placeholder="First Name" />
      <input {...form.register('lastName')} placeholder="Last Name" />
      <button type="submit">Submit</button>
    </form>
  );
}
Renders a form element with inputs for firstName and lastName. The inputs are registered to the form state. A submit button triggers form submission, logging form values to the console.
export default MyFormComponent;
Exports the MyFormComponent for use in other parts of the application.