Blog>
Snippets

Initializing TanStack Form with Basic Fields

Demonstrate how to set up a TanStack Form instance and define simple text input fields with initial values.
import { useForm } from '@tanstack/react-form';
Import the useForm hook from the '@tanstack/react-form' package.
function MyForm() {
Define a functional component where our form will be initialized.
  const { register } = useForm({
    defaultValues: {
      firstName: '',
      lastName: ''
    }
  });
Initialize the useForm hook with default values for the form's fields.
  return (
    <form>
      <label htmlFor='firstName'>First Name</label>
      <input id='firstName' {...register('firstName')} />
      <label htmlFor='lastName'>Last Name</label>
      <input id='lastName' {...register('lastName')} />
    </form>
  );
}
Render the form with two input fields for first name and last name, utilizing the register function provided by useForm for binding.
export default MyForm;
Export the form component for use in other parts of the application.