Blog>
Snippets

Initializing TanStack Form with Default Values

Demonstrate how to set up a TanStack Form with useForm hook by providing default values for form fields.
import { useForm } from '@tanstack/react-form';
First, import the useForm hook from TanStack Form to enable form state management.
const form = useForm({
  initialValues: {
    username: '',
    password: '',
  },
});
Initialize the form with default values using the useForm hook. Here, both username and password fields are set to empty strings.
<form onSubmit={form.handleSubmit()}>
  <input {...form.fields.username.getInputProps()} />
  <input {...form.fields.password.getInputProps()} type="password" />
  <button type="submit">Submit</button>
</form>
Render the form in the UI. Connect the input fields to the useForm instance to ensure they are properly managed. The handleSubmit method is used to handle form submission.