Next.js course ยท Module 6: Forms and Server Actions

Creating Forms in React and Next.js

15 min read ยท
In this lesson4

Forms are a fundamental element of interactive web applications. They allow users to input data, which can then be processed by the application. In the React and Next.js environment, creating forms can be achieved in various ways - from simple native solutions to advanced libraries. In this module, we will look at different approaches to form implementation.

Basic Forms in React

In its most basic form, a form in React is similar to a traditional HTML form, but with an additional layer of state management.

Controlled Form Components

The most commonly used approach in React is "controlled components", where the value of each form element is maintained in React state:

import { useState, FormEvent } from 'react';

export default function SimpleForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    console.log('Form data:', { name, email, message });

    // Here you can send data to the API
    // fetch('/api/contact', {
    //   method: 'POST',
    //   body: JSON.stringify({ name, email, message }),
    //   headers: { 'Content-Type': 'application/json' }
    // })

    // Optionally reset the form
    setName('');
    setEmail('');
    setMessage('');
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="name" className="block text-sm font-medium text-gray-700">
          Full name
        </label>
        <input
          type="text"
          id="name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
          required
        />
      </div>

      <div>
        <label htmlFor="email" className="block text-sm font-medium text-gray-700">
          Email
        </label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
          required
        />
      </div>

      <div>
        <label htmlFor="message" className="block text-sm font-medium text-gray-700">
          Message
        </label>
        <textarea
          id="message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          rows={4}
          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
          required
        />
      </div>

      <button
        type="submit"
        className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
      >
        Send
      </button>
    </form>
  );
}

In the example above:

  1. Each form field is connected to a corresponding state variable
  2. The onChange event updates state for each field
  3. The onSubmit event for the whole form handles data submission
  4. Using event.preventDefault() prevents the default page refresh

Managing Multiple Form Fields

When a form has many fields, maintaining a separate state for each one can be cumbersome. A more scalable approach is to use a single state object:

import { useState, ChangeEvent, FormEvent } from 'react';

interface FormData {
  name: string;
  email: string;
  subject: string;
  message: string;
  agreeToTerms: boolean;
}

export default function ContactForm() {
  const [formData, setFormData] = useState<FormData>({
    name: '',
    email: '',
    subject: '',
    message: '',
    agreeToTerms: false
  });

  const [errors, setErrors] = useState<Partial<FormData>>({});

  function handleChange(e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) {
    const { name, value, type } = e.target;
    const checked = (e.target as HTMLInputElement).checked;

    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));

    // Reset error during editing
    if (errors[name as keyof FormData]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  }

  function validateForm(): boolean {
    const newErrors: Partial<FormData> = {};
    let isValid = true;

    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
      isValid = false;
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
      isValid = false;
    } else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      newErrors.email = 'Email is invalid';
      isValid = false;
    }

    if (!formData.message.trim()) {
      newErrors.message = 'Message is required';
      isValid = false;
    }

    if (!formData.agreeToTerms) {
      newErrors.agreeToTerms = 'You must agree to the terms';
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  }

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();

    if (validateForm()) {
      console.log('Submitting form:', formData);
      // Send to API...

      // Reset form after successful submission
      setFormData({
        name: '',
        email: '',
        subject: '',
        message: '',
        agreeToTerms: false
      });
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="name" className="block text-sm font-medium">
          Full name *
        </label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          className={`mt-1 block w-full rounded-md ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
        />
        {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name}</p>}
      </div>

      <div>
        <label htmlFor="email" className="block text-sm font-medium">
          Email *
        </label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          className={`mt-1 block w-full rounded-md ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
        />
        {errors.email && <p className="text-red-500 text-xs mt-1">{errors.email}</p>}
      </div>

      <div>
        <label htmlFor="subject" className="block text-sm font-medium">
          Subject
        </label>
        <select
          id="subject"
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          className="mt-1 block w-full rounded-md border-gray-300"
        >
          <option value="">Select subject</option>
          <option value="general">General inquiry</option>
          <option value="support">Technical support</option>
          <option value="feedback">Feedback</option>
        </select>
      </div>

      <div>
        <label htmlFor="message" className="block text-sm font-medium">
          Message *
        </label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          rows={4}
          className={`mt-1 block w-full rounded-md ${errors.message ? 'border-red-500' : 'border-gray-300'}`}
        />
        {errors.message && <p className="text-red-500 text-xs mt-1">{errors.message}</p>}
      </div>

      <div className="flex items-center">
        <input
          type="checkbox"
          id="agreeToTerms"
          name="agreeToTerms"
          checked={formData.agreeToTerms}
          onChange={handleChange}
          className={`h-4 w-4 ${errors.agreeToTerms ? 'border-red-500' : 'border-gray-300'}`}
        />
        <label htmlFor="agreeToTerms" className="ml-2 block text-sm">
          I agree to the terms and privacy policy *
        </label>
        {errors.agreeToTerms && (
          <p className="text-red-500 text-xs ml-2">{errors.agreeToTerms}</p>
        )}
      </div>

      <button
        type="submit"
        className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
      >
        Send message
      </button>
    </form>
  );
}

This approach offers the following advantages:

  1. A single handleChange function handles all fields
  2. Dynamic state updates thanks to the [name]: value syntax
  3. TypeScript typing ensures type safety
  4. Validation with error messages improves user experience

Forms in Next.js with Server Actions

Next.js 13+ introduced Server Actions, which enable direct form processing on the server without the need to create separate API endpoints.

Basic Form with Server Action

// app/signup/page.tsx
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { registerUser } from './actions';

export default function SignupPage() {
  const router = useRouter();
  const [error, setError] = useState<string>('');
  const [loading, setLoading] = useState(false);

  async function handleSubmit(formData: FormData) {
    setLoading(true);
    setError('');

    try {
      // Call Server Action
      const result = await registerUser(formData);

      if (result.success) {
        // Redirect after successful registration
        router.push('/signup/confirm');
      } else {
        // Display error
        setError(result.error || 'Something went wrong');
      }
    } catch (e) {
      setError('An unexpected error occurred.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6">Registration</h1>

      {error && (
        <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <form action={handleSubmit}>
        <div className="mb-4">
          <label htmlFor="name" className="block text-sm font-medium mb-1">
            Full name
          </label>
          <input
            type="text"
            id="name"
            name="name"
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <div className="mb-4">
          <label htmlFor="email" className="block text-sm font-medium mb-1">
            Email
          </label>
          <input
            type="email"
            id="email"
            name="email"
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <div className="mb-4">
          <label htmlFor="password" className="block text-sm font-medium mb-1">
            Password
          </label>
          <input
            type="password"
            id="password"
            name="password"
            required
            minLength={8}
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
        >
          {loading ? 'Registering...' : 'Sign up'}
        </button>
      </form>
    </div>
  );
}

And here is the Server Action file:

// app/signup/actions.ts
'use server';

import { z } from 'zod';

// Form validation schema
const UserSchema = z.object({
  name: z.string().min(2, { message: 'Name is too short' }),
  email: z.string().email({ message: 'Invalid email address' }),
  password: z.string().min(8, { message: 'Password must be at least 8 characters' })
});

type SignupResult =
  | { success: true; userId: string }
  | { success: false; error: string };

export async function registerUser(formData: FormData): Promise<SignupResult> {
  // 1. Validate form data
  const validatedFields = UserSchema.safeParse({
    name: formData.get('name'),
    email: formData.get('email'),
    password: formData.get('password')
  });

  if (!validatedFields.success) {
    return {
      success: false,
      error: validatedFields.error.errors[0]?.message || 'Invalid form data'
    };
  }

  const { name, email, password } = validatedFields.data;

  try {
    // 2. Check if user already exists
    const existingUser = false; // Here should be the actual database check logic

    if (existingUser) {
      return {
        success: false,
        error: 'A user with this email address already exists'
      };
    }

    // 3. Create new user (in a real application - save to database)
    // const newUser = await db.user.create({ data: { name, email, password: hashedPassword } });

    // 4. Additional operations - sending welcome email, logging in, etc.
    // await sendWelcomeEmail(email, name);

    return {
      success: true,
      userId: '123' // In a real application, the created user ID
    };
  } catch (error) {
    console.error('Registration error:', error);
    return {
      success: false,
      error: 'An error occurred during registration. Please try again later.'
    };
  }
}

Advantages of Server Actions:

  1. Simplified architecture - no need to create separate API Routes
  2. Progressive enhancement - forms work even without JavaScript
  3. Secure data processing - verification and processing logic runs on the server
  4. End-to-end typing - TypeScript can provide typing from form to database

Forms with Loading States and Validation

We can combine Server Actions with React Hooks to provide an even better user experience:

// app/contact/page.tsx
'use client';

import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { submitContactForm } from './actions';

// Button component with loading state handling
function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button
      type="submit"
      disabled={pending}
      className="bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
    >
      {pending ? 'Sending...' : 'Send message'}
    </button>
  );
}

export default function ContactPage() {
  // Initial form state
  const initialState = {
    message: '',
    errors: {},
    success: false
  };

  // Using the useActionState hook to manage form state
  const [state, formAction] = useActionState(submitContactForm, initialState);

  return (
    <div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6">Contact form</h1>

      {state.success ? (
        <div className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
          Thank you for your message! We will respond as soon as possible.
        </div>
      ) : (
        <form action={formAction} className="space-y-4">
          {state.message && (
            <div className="p-3 bg-red-100 border border-red-400 text-red-700 rounded">
              {state.message}
            </div>
          )}

          <div>
            <label htmlFor="name" className="block text-sm font-medium mb-1">
              Full name *
            </label>
            <input
              type="text"
              id="name"
              name="name"
              className={`w-full px-3 py-2 border rounded-md ${
                state.errors?.name ? 'border-red-500' : 'border-gray-300'
              }`}
            />
            {state.errors?.name && (
              <p className="text-red-500 text-xs mt-1">{state.errors.name}</p>
            )}
          </div>

          <div>
            <label htmlFor="email" className="block text-sm font-medium mb-1">
              Email *
            </label>
            <input
              type="email"
              id="email"
              name="email"
              className={`w-full px-3 py-2 border rounded-md ${
                state.errors?.email ? 'border-red-500' : 'border-gray-300'
              }`}
            />
            {state.errors?.email && (
              <p className="text-red-500 text-xs mt-1">{state.errors.email}</p>
            )}
          </div>

          <div>
            <label htmlFor="message" className="block text-sm font-medium mb-1">
              Message *
            </label>
            <textarea
              id="message"
              name="message"
              rows={4}
              className={`w-full px-3 py-2 border rounded-md ${
                state.errors?.messageContent ? 'border-red-500' : 'border-gray-300'
              }`}
            />
            {state.errors?.messageContent && (
              <p className="text-red-500 text-xs mt-1">{state.errors.messageContent}</p>
            )}
          </div>

          <SubmitButton />
        </form>
      )}
    </div>
  );
}

And the related actions file:

// app/contact/actions.ts
'use server';

import { z } from 'zod';

// Validation schema
const ContactSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Invalid email address'),
  messageContent: z.string().min(10, 'Message must be at least 10 characters')
});

// Form state type
type FormState = {
  message: string;
  errors?: Record<string, string>;
  success: boolean;
};

export async function submitContactForm(prevState: FormState, formData: FormData): Promise<FormState> {
  // Prepare data for validation
  const validationData = {
    name: formData.get('name'),
    email: formData.get('email'),
    messageContent: formData.get('message')
  };

  // Validation
  const result = ContactSchema.safeParse(validationData);

  if (!result.success) {
    // Prepare error structure
    const errors: Record<string, string> = {};
    result.error.errors.forEach(error => {
      if (error.path[0]) {
        errors[error.path[0].toString()] = error.message;
      }
    });

    return {
      message: 'The form contains errors. Fix them and try again.',
      errors,
      success: false
    };
  }

  try {
    // Simulate network delay
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Here would be the code to send the message, e.g. save to database or send email
    // await sendContactEmail(result.data);

    // Return success information
    return {
      message: '',
      success: true
    };
  } catch (error) {
    return {
      message: 'An error occurred while sending the message. Please try again later.',
      success: false
    };
  }
}

In this example, we use:

  1. useActionState - for managing form state between client and server
  2. useFormStatus - for tracking form submission status (pending)
  3. Zod - for validating form data on the server
  4. Functional components - for organizing UI logic

Beyond the native approach, there are several excellent libraries that simplify working with forms in React and Next.js.

React Hook Form

React Hook Form is one of the most popular form handling libraries in React, which minimizes rendering and optimizes performance.

import { useForm, SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

// Validation schema definition
const loginFormSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(6, 'Password must be at least 6 characters')
});

// Form data type inferred from Zod schema
type LoginFormInputs = z.infer<typeof loginFormSchema>;

export default function LoginForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm<LoginFormInputs>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      email: '',
      password: ''
    }
  });

  const onSubmit: SubmitHandler<LoginFormInputs> = async (data) => {
    try {
      // Simulate network delay
      await new Promise(resolve => setTimeout(resolve, 1000));

      console.log('Login data:', data);
      // In a real application: call login API
      // await signIn('credentials', { email: data.email, password: data.password });
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <label htmlFor="email" className="block text-sm font-medium">
          Email
        </label>
        <input
          id="email"
          type="email"
          className={`mt-1 block w-full rounded-md ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
          {...register('email')}
        />
        {errors.email && (
          <p className="text-red-500 text-xs mt-1">{errors.email.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="password" className="block text-sm font-medium">
          Password
        </label>
        <input
          id="password"
          type="password"
          className={`mt-1 block w-full rounded-md ${errors.password ? 'border-red-500' : 'border-gray-300'}`}
          {...register('password')}
        />
        {errors.password && (
          <p className="text-red-500 text-xs mt-1">{errors.password.message}</p>
        )}
      </div>

      <button
        type="submit"
        disabled={isSubmitting}
        className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
      >
        {isSubmitting ? 'Logging in...' : 'Log in'}
      </button>
    </form>
  );
}

Advantages of React Hook Form:

  1. Performance - minimally re-renders components
  2. Easy integration - works with unmodified HTML form elements
  3. Advanced validation - native integration with Zod, Yup, and other libraries
  4. Unconventional validation forms - validation dependent on other fields, conditional validation, etc.

Formik

Formik is another popular form library in React that offers a more declarative approach:

import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

// Yup validation schema
const CheckoutSchema = Yup.object().shape({
  firstName: Yup.string().required('Name is required'),
  lastName: Yup.string().required('Last name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
  address: Yup.string().required('Address is required'),
  city: Yup.string().required('City is required'),
  postalCode: Yup.string()
    .matches(/^\d{2}-\d{3}$/, 'Invalid postal code (e.g. 00-000)')
    .required('Postal code is required'),
  paymentMethod: Yup.string().required('Select payment method')
});

export default function CheckoutForm() {
  return (
    <div className="max-w-md mx-auto mt-10">
      <h1 className="text-2xl font-bold mb-6">Order Checkout</h1>

      <Formik
        initialValues={{
          firstName: '',
          lastName: '',
          email: '',
          address: '',
          city: '',
          postalCode: '',
          paymentMethod: ''
        }}
        validationSchema={CheckoutSchema}
        onSubmit={async (values, { setSubmitting, resetForm }) => {
          try {
            // Simulate delay
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.log('Checkout data:', values);

            // In a real application: call API
            // await processCheckout(values);

            resetForm();
            alert('Order accepted!');
          } catch (error) {
            console.error('Checkout error:', error);
            alert('An error occurred while placing the order');
          } finally {
            setSubmitting(false);
          }
        }}
      >
        {({ isSubmitting }) => (
          <Form className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="firstName" className="block text-sm font-medium">
                  First name
                </label>
                <Field
                  id="firstName"
                  name="firstName"
                  type="text"
                  className="mt-1 block w-full rounded-md border-gray-300"
                />
                <ErrorMessage name="firstName" component="div" className="text-red-500 text-xs mt-1" />
              </div>

              <div>
                <label htmlFor="lastName" className="block text-sm font-medium">
                  Last name
                </label>
                <Field
                  id="lastName"
                  name="lastName"
                  type="text"
                  className="mt-1 block w-full rounded-md border-gray-300"
                />
                <ErrorMessage name="lastName" component="div" className="text-red-500 text-xs mt-1" />
              </div>
            </div>

            <div>
              <label htmlFor="email" className="block text-sm font-medium">
                Email
              </label>
              <Field
                id="email"
                name="email"
                type="email"
                className="mt-1 block w-full rounded-md border-gray-300"
              />
              <ErrorMessage name="email" component="div" className="text-red-500 text-xs mt-1" />
            </div>

            <div>
              <label htmlFor="address" className="block text-sm font-medium">
                Address
              </label>
              <Field
                id="address"
                name="address"
                type="text"
                className="mt-1 block w-full rounded-md border-gray-300"
              />
              <ErrorMessage name="address" component="div" className="text-red-500 text-xs mt-1" />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="city" className="block text-sm font-medium">
                  City
                </label>
                <Field
                  id="city"
                  name="city"
                  type="text"
                  className="mt-1 block w-full rounded-md border-gray-300"
                />
                <ErrorMessage name="city" component="div" className="text-red-500 text-xs mt-1" />
              </div>

              <div>
                <label htmlFor="postalCode" className="block text-sm font-medium">
                  Postal code
                </label>
                <Field
                  id="postalCode"
                  name="postalCode"
                  type="text"
                  className="mt-1 block w-full rounded-md border-gray-300"
                />
                <ErrorMessage name="postalCode" component="div" className="text-red-500 text-xs mt-1" />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-2">
                Payment method
              </label>

              <div className="space-y-2">
                <label className="flex items-center">
                  <Field type="radio" name="paymentMethod" value="card" className="mr-2" />
                  Credit card
                </label>

                <label className="flex items-center">
                  <Field type="radio" name="paymentMethod" value="blik" className="mr-2" />
                  BLIK
                </label>

                <label className="flex items-center">
                  <Field type="radio" name="paymentMethod" value="transfer" className="mr-2" />
                  Bank transfer
                </label>
              </div>

              <ErrorMessage name="paymentMethod" component="div" className="text-red-500 text-xs mt-1" />
            </div>

            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
            >
              {isSubmitting ? 'Processing...' : 'Place order'}
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

Advantages of Formik:

  1. Declarative API - Form, Field and ErrorMessage components
  2. Good documentation - extensive documentation and examples
  3. Maturity - stable and proven in production
  4. Integration with Yup - easy validation with the Yup library

Summary

In this module, we explored different approaches to creating forms in React and Next.js:

  1. Native React forms - controlled components with local state
  2. Server Actions in Next.js - a new server-side approach
  3. React Hook Form - an efficient library with minimal rendering
  4. Formik - a mature library with declarative API

Choosing the right approach depends on the specifics of the project:

  • For simple forms: native React solutions
  • For Next.js applications: Server Actions with Progressive Enhancement
  • For complex client-side forms: React Hook Form or Formik

Regardless of the chosen approach, it is worth keeping in mind a few good practices:

  • Validation at multiple levels - client + server
  • Accessibility - proper labels, ARIA attributes, keyboard support
  • Feedback - loading states, errors, confirmations
  • Security - CSRF protection, server-side data validation

In the next modules, we will explore more advanced form handling techniques, including file uploads, multi-step forms, and integrations with external APIs.

Code for this lesson: App.tsx
// Demo: Creating forms in React and Next.js
// Form basics: controlled components, events, submit
import React, { useState, FormEvent } from 'react';

// In React forms work as "controlled components"
// React state controls form field values
// onChange updates state -> React re-renders input with new value

// Basic pattern:
// const [value, setValue] = useState('');
// <input value={value} onChange={e => setValue(e.target.value)} />

interface ContactData {
  name: string;
  email: string;
  subject: string;
  message: string;
  priority: 'low' | 'medium' | 'high';
}

const initialData: ContactData = {
  name: '',
  email: '',
  subject: '',
  message: '',
  priority: 'medium',
};

function FormInput({ label, id, type = 'text', value, onChange, placeholder }: {
  label: string; id: string; type?: string;
  value: string; onChange: (val: string) => void; placeholder?: string;
}) {
  return (
    <div style={{ marginBottom: '16px' }}>
      <label htmlFor={id} style={{
        display: 'block', color: '#b0bec5', fontSize: '0.85rem', marginBottom: '6px',
      }}>{label}</label>
      <input
        id={id} type={type} value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: '100%', padding: '12px 16px', boxSizing: 'border-box',
          background: 'rgba(255,255,255,0.05)',
          border: '1px solid rgba(100,255,218,0.3)',
          borderRadius: '8px', color: '#fff', fontSize: '1rem', outline: 'none',
        }}
      />
    </div>
  );
}

export default function ContactFormDemo() {
  const [formData, setFormData] = useState<ContactData>(initialData);
  const [submitted, setSubmitted] = useState(false);
  const [submittedData, setSubmittedData] = useState<ContactData | null>(null);

  const updateField = (field: keyof ContactData) => (value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault(); // Prevent default page reload
    setSubmittedData(formData);
    setSubmitted(true);
  };

  const handleReset = () => {
    setFormData(initialData);
    setSubmitted(false);
    setSubmittedData(null);
  };

  const priorityColors = { low: '#4caf50', medium: '#ff9800', high: '#f44336' };

  return (
    <div style={{
      background: '#0f0f23', minHeight: '100vh', padding: '24px',
      color: '#fff', fontFamily: 'system-ui, sans-serif',
      display: 'flex', justifyContent: 'center',
    }}>
      <div style={{ maxWidth: '500px', width: '100%' }}>
        <h1 style={{ color: '#64ffda', marginBottom: '4px' }}>Quantum Contact Form</h1>
        <p style={{ color: '#b0bec5', marginBottom: '24px', fontSize: '0.9rem' }}>
          Controlled components - React manages form state
        </p>

        <form onSubmit={handleSubmit}>
          <FormInput label="Name" id="name" value={formData.name}
            onChange={updateField('name')} placeholder="Agent name..." />
          <FormInput label="Email" id="email" type="email" value={formData.email}
            onChange={updateField('email')} placeholder="agent@quantum.io" />
          <FormInput label="Subject" id="subject" value={formData.subject}
            onChange={updateField('subject')} placeholder="Subject..." />

          <div style={{ marginBottom: '16px' }}>
            <label style={{ display: 'block', color: '#b0bec5', fontSize: '0.85rem', marginBottom: '8px' }}>
              Priority
            </label>
            <div style={{ display: 'flex', gap: '8px' }}>
              {(['low', 'medium', 'high'] as const).map(p => (
                <button key={p} type="button"
                  onClick={() => updateField('priority')(p)}
                  style={{
                    flex: 1, padding: '10px', borderRadius: '8px',
                    background: formData.priority === p ? `${priorityColors[p]}20` : 'transparent',
                    border: `1px solid ${formData.priority === p ? priorityColors[p] : 'rgba(255,255,255,0.1)'}`,
                    color: formData.priority === p ? priorityColors[p] : '#78909c',
                    cursor: 'pointer', textTransform: 'capitalize',
                  }}
                >{p}</button>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: '16px' }}>
            <label htmlFor="message" style={{
              display: 'block', color: '#b0bec5', fontSize: '0.85rem', marginBottom: '6px',
            }}>Message</label>
            <textarea id="message" rows={4} value={formData.message}
              onChange={e => updateField('message')(e.target.value)}
              style={{
                width: '100%', padding: '12px', boxSizing: 'border-box',
                background: 'rgba(255,255,255,0.05)',
                border: '1px solid rgba(100,255,218,0.3)',
                borderRadius: '8px', color: '#fff', fontSize: '1rem',
                outline: 'none', resize: 'vertical',
              }}
            />
          </div>

          <div style={{ display: 'flex', gap: '10px' }}>
            <button type="submit" style={{
              flex: 2, background: '#64ffda', color: '#0f0f23',
              border: 'none', padding: '14px', borderRadius: '8px',
              cursor: 'pointer', fontWeight: 600, fontSize: '1rem',
            }}>Submit</button>
            <button type="button" onClick={handleReset} style={{
              flex: 1, background: 'transparent', color: '#78909c',
              border: '1px solid rgba(255,255,255,0.1)', padding: '14px',
              borderRadius: '8px', cursor: 'pointer',
            }}>Reset</button>
          </div>
        </form>

        {/* Live React state preview */}
        <div style={{
          marginTop: '24px', background: 'rgba(0,0,0,0.3)',
          borderRadius: '8px', padding: '16px',
        }}>
          <h4 style={{ color: '#78909c', marginBottom: '8px', fontSize: '0.8rem' }}>
            React State (live):
          </h4>
          <pre style={{ margin: 0, color: '#b0bec5', fontSize: '0.75rem', lineHeight: 1.5 }}>
            {JSON.stringify(formData, null, 2)}
          </pre>
        </div>

        {submitted && submittedData && (
          <div style={{
            marginTop: '16px', background: 'rgba(76,175,80,0.1)',
            border: '1px solid rgba(76,175,80,0.3)',
            borderRadius: '8px', padding: '16px',
          }}>
            <h4 style={{ color: '#4caf50', marginBottom: '8px' }}>Sent!</h4>
            <p style={{ color: '#b0bec5', fontSize: '0.85rem', margin: 0 }}>
              From: {submittedData.name} ({submittedData.email})
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. In React, an <input> element in a form is controlled when:

  1. QuestionForm Elements in React

Useful articles