Blog>
Snippets

Initializing useForm Hook for Basic Form Handling

Demonstrate initializing the useForm hook in TanStack Form to manage a simple login form including basic fields such as email and password.
import { useForm } from '@tanstack/react-form';
First, import the useForm hook from '@tanstack/react-form' to use it in our component.
function LoginForm() {
  const form = useForm({
    defaultValues: {
      email: '',
      password: ''
    },
    onSubmit: async values => {
      // Handle form submission
      console.log('Form Submitted:', values);
    }
  });

  return (
    // Form rendering and logic goes here
  );
}
Initialize the useForm hook with default values for email and password. Define an onSubmit function to handle form submission, logging submitted values for demonstration.
const { Form, Field } = form;
return (
  <Form>
    <div>
      <Field name="email">
        {({ getInputProps }) => <input type="email" {...getInputProps()} required />}
      </Field>
    </div>
    <div>
      <Field name="password">
        {({ getInputProps }) => <input type="password" {...getInputProps()} required />}
      </Field>
    </div>
    <button type="submit">Login</button>
  </Form>
);
Render the form with email and password fields using the Field component. Use getInputProps to spread the necessary props to each input. Include a submit button to submit the form.