Blog>
Snippets

Creating a Simple Login Form with TanStack Form

Demonstrate creating a basic login form including username and password fields, showcasing how to handle form state and submission.
import { useForm, useController } from 'tanstack-form-core';
import { useState } from 'react';
Imports the necessary hooks from TanStack Form and React.
const Login = () => {
  // Using TanStack Form's useForm hook to manage form state
  const form = useForm({
    defaultValues: {
      username: '',
      password: ''
    }
  });
Defines the Login component and initializes the form with default values for the username and password.
const { field: usernameField } = useController({
    name: 'username',
    control: form.control,
  });

  const { field: passwordField } = useController({
    name: 'password',
    control: form.control,
  });
Creates controllers for the username and password fields to connect them with the form state.
const handleSubmit = async (e) => {
    e.preventDefault();
    // Perform the form submission logic, possibly including validation
    console.log(form.getValues());
  };
Defines the submit handler for the form, which prevents the default form submission behavior and logs the form values.
return (
    <form onSubmit={handleSubmit}>
      <input {...usernameField} placeholder="Username" />
      <input type="password" {...passwordField} placeholder="Password" />
      <button type="submit">Login</button>
    </form>
  );
};
Renders the form with the connected username and password input fields and a submit button.
export default Login;
Exports the Login component for use elsewhere in the application.