Blog>
Snippets

Initializing a Basic TanStack Form in React

Demonstrates setting up a basic form using TanStack hooks in a React component, outlining the structure and initial state.
import React, { useState } from 'react';
import { useForm } from '@tanstack/react-form';
Imports React, useState hook for managing form state, and useForm from TanStack for handling form data.
function BasicForm() {
  const [formData, setFormData] = useState({ name: '', email: '' });
Defines a functional component and initializes form data state with name and email fields.
  const { Form, useField } = useForm({
    defaultValues: formData,
    onSubmit: async(values) => {
      console.log(values);
      // Submit form values
    },
  });
Uses useForm hook to handle the form lifecycle, including default values and submission logic.
  const nameField = useField('name');
  const emailField = useField('email');
Utilizes useField hook to manage individual form fields.
  return (
    <Form>
      <div>
        <label>Name:</label>
        <input {...nameField.getInputProps()} />
      </div>
      <div>
        <label>Email:</label>
        <input {...emailField.getInputProps()} />
      </div>
      <button type='submit'>Submit</button>
    </Form>
  );
}
Renders the form with input fields for name and email. It uses spread attributes to pass down input props.
export default BasicForm;
Exports the form component for use in other parts of the application.