Blog>
Snippets

Initializing TanStack Form with useForm Hook

Demonstrate how to set up a basic form using the useForm hook in TanStack Form, including creating form fields and submitting form data.
import { useForm } from 'tanstack-form';

function MyForm() {
  const { form, handleSubmit } = useForm({
    defaultValues: {
      username: '',
      password: ''
    }
  });

  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...form.getInputProps('username')} />
      <input {...form.getInputProps('password')} type='password' />
      <button type='submit'>Submit</button>
    </form>
  );
}
This code snippet demonstrates how to setup a basic form using the useForm hook from TanStack Form. It initializes the form with default values for 'username' and 'password' fields. The getInputProps method is used to bind input elements to the form state. The form data is logged to the console upon form submission.