Kurs Next.js · Moduł 6: Formularze i Server Actions

Tworzenie formularzy w React i Next.js

14 min czytania ·
W tej lekcji4

Formularze są fundamentalnym elementem interaktywnych aplikacji webowych. Pozwalają użytkownikom na wprowadzanie danych, które następnie mogą być przetwarzane przez aplikację. W środowisku React i Next.js tworzenie formularzy może być realizowane na różne sposoby - od prostych rozwiązań natywnych po zaawansowane biblioteki. W tym module przyjrzymy się różnym podejściom do implementacji formularzy.

Podstawowe formularze w React

W najbardziej podstawowej formie, formularz w React jest podobny do tradycyjnego formularza HTML, ale z dodatkową warstwą zarządzania stanem.

Kontrolowane komponenty formularza

Najczęściej stosowanym podejściem w React są "kontrolowane komponenty", gdzie wartość każdego elementu formularza jest utrzymywana w stanie React:

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('Dane formularza:', { name, email, message });

    // Tutaj możesz wysłać dane do API
    // fetch('/api/contact', {
    //   method: 'POST',
    //   body: JSON.stringify({ name, email, message }),
    //   headers: { 'Content-Type': 'application/json' }
    // })

    // Opcjonalnie zresetuj formularz
    setName('');
    setEmail('');
    setMessage('');
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="name" className="block text-sm font-medium text-gray-700">
          Imię i nazwisko
        </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">
          Wiadomość
        </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"
      >
        Wyślij
      </button>
    </form>
  );
}

W powyższym przykładzie:

  1. Każde pole formularza jest połączone z odpowiednią zmienną stanu
  2. Zdarzenie onChange aktualizuje stan dla każdego pola
  3. Zdarzenie onSubmit całego formularza obsługuje przesłanie danych
  4. Użycie event.preventDefault() zapobiega domyślnemu odświeżaniu strony

Zarządzanie wieloma polami formularza

Kiedy formularz ma wiele pól, utrzymywanie osobnego stanu dla każdego z nich może być uciążliwe. Bardziej skalowalne podejście to używanie jednego obiektu stanu:

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
    }));

    // Resetowanie błędu podczas edycji
    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 = 'Imię jest wymagane';
      isValid = false;
    }

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

    if (!formData.message.trim()) {
      newErrors.message = 'Wiadomość jest wymagana';
      isValid = false;
    }

    if (!formData.agreeToTerms) {
      newErrors.agreeToTerms = 'Wymagana jest zgoda na warunki';
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  }

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

    if (validateForm()) {
      console.log('Przesyłanie formularza:', formData);
      // Wysyłka do API...

      // Resetowanie formularza po udanym przesłaniu
      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">
          Imię i nazwisko *
        </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">
          Temat
        </label>
        <select
          id="subject"
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          className="mt-1 block w-full rounded-md border-gray-300"
        >
          <option value="">Wybierz temat</option>
          <option value="general">Zapytanie ogólne</option>
          <option value="support">Wsparcie techniczne</option>
          <option value="feedback">Opinia</option>
        </select>
      </div>

      <div>
        <label htmlFor="message" className="block text-sm font-medium">
          Wiadomość *
        </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">
          Zgadzam się na warunki i politykę prywatności *
        </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"
      >
        Wyślij wiadomość
      </button>
    </form>
  );
}

To podejście oferuje następujące zalety:

  1. Pojedyncza funkcja handleChange obsługuje wszystkie pola
  2. Dynamiczne aktualizowanie stanu dzięki składni [name]: value
  3. Typowanie TypeScript zapewnia bezpieczeństwo typów
  4. Walidacja z komunikatami o błędach poprawia doświadczenie użytkownika

Formularze w Next.js z Server Actions

Next.js 13+ wprowadził Server Actions, które umożliwiają bezpośrednie przetwarzanie formularzy na serwerze bez konieczności tworzenia osobnych endpointów API.

Podstawowy formularz z 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 {
      // Wywołanie Server Action
      const result = await registerUser(formData);

      if (result.success) {
        // Przekierowanie po udanej rejestracji
        router.push('/signup/confirm');
      } else {
        // Wyświetlenie błędu
        setError(result.error || 'Something went wrong');
      }
    } catch (e) {
      setError('Wystąpił nieoczekiwany błąd.');
    } 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">Rejestracja</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">
            Imię i nazwisko
          </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">
            Hasło
          </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 ? 'Rejestracja...' : 'Zarejestruj się'}
        </button>
      </form>
    </div>
  );
}

A oto plik z Server Action:

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

import { z } from 'zod';

// Schemat walidacji formularza
const UserSchema = z.object({
  name: z.string().min(2, { message: 'Imię jest zbyt krótkie' }),
  email: z.string().email({ message: 'Nieprawidłowy adres email' }),
  password: z.string().min(8, { message: 'Hasło musi mieć co najmniej 8 znaków' })
});

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

export async function registerUser(formData: FormData): Promise<SignupResult> {
  // 1. Walidacja danych formularza
  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 || 'Niepoprawne dane formularza'
    };
  }

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

  try {
    // 2. Sprawdzenie czy użytkownik już istnieje
    const existingUser = false; // Tu powinna być prawdziwa logika sprawdzenia w bazie danych

    if (existingUser) {
      return {
        success: false,
        error: 'Użytkownik o podanym adresie email już istnieje'
      };
    }

    // 3. Tworzenie nowego użytkownika (w rzeczywistej aplikacji - zapis do bazy)
    // const newUser = await db.user.create({ data: { name, email, password: hashedPassword } });

    // 4. Dodatkowe operacje - wysyłka emaila powitalnego, logowanie, itp.
    // await sendWelcomeEmail(email, name);

    return {
      success: true,
      userId: '123' // W rzeczywistej aplikacji id utworzonego użytkownika
    };
  } catch (error) {
    console.error('Registration error:', error);
    return {
      success: false,
      error: 'Wystąpił błąd podczas rejestracji. Spróbuj ponownie później.'
    };
  }
}

Zalety Server Actions:

  1. Uproszczona architektura - nie trzeba tworzyć osobnych API Routes
  2. Progresywne ulepszanie - formularze działają nawet bez JavaScript
  3. Bezpieczne przetwarzanie danych - logika weryfikacji i przetwarzania danych jest wykonywana na serwerze
  4. Typowanie end-to-end - TypeScript może zapewnić typowanie od formularza po bazę danych

Formularze ze stanami ładowania i walidacją

Możemy połączyć Server Actions z React Hooks, aby zapewnić jeszcze lepsze doświadczenie użytkownika:

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

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

// Komponent przycisku z obsługą stanu ładowania
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 ? 'Wysyłanie...' : 'Wyślij wiadomość'}
    </button>
  );
}

export default function ContactPage() {
  // Początkowy stan formularza
  const initialState = {
    message: '',
    errors: {},
    success: false
  };

  // Użycie hooka useActionState do zarządzania stanem formularza
  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">Formularz kontaktowy</h1>

      {state.success ? (
        <div className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
          Dziękujemy za wiadomość! Odpowiemy najszybciej jak to możliwe.
        </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">
              Imię i nazwisko *
            </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">
              Wiadomość *
            </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>
  );
}

I powiązany plik akcji:

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

import { z } from 'zod';

// Schemat walidacji
const ContactSchema = z.object({
  name: z.string().min(1, 'Imię jest wymagane'),
  email: z.string().email('Nieprawidłowy adres email'),
  messageContent: z.string().min(10, 'Wiadomość musi mieć co najmniej 10 znaków')
});

// Typ stanu formularza
type FormState = {
  message: string;
  errors?: Record<string, string>;
  success: boolean;
};

export async function submitContactForm(prevState: FormState, formData: FormData): Promise<FormState> {
  // Przygotowanie danych do walidacji
  const validationData = {
    name: formData.get('name'),
    email: formData.get('email'),
    messageContent: formData.get('message')
  };

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

  if (!result.success) {
    // Przygotowanie struktury błędów
    const errors: Record<string, string> = {};
    result.error.errors.forEach(error => {
      if (error.path[0]) {
        errors[error.path[0].toString()] = error.message;
      }
    });

    return {
      message: 'Formularz zawiera błędy. Popraw je i spróbuj ponownie.',
      errors,
      success: false
    };
  }

  try {
    // Symulacja opóźnienia sieciowego
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Tutaj byłby kod do wysyłki wiadomości, np. zapis do bazy lub wysyłka emaila
    // await sendContactEmail(result.data);

    // Zwracamy informację o sukcesie
    return {
      message: '',
      success: true
    };
  } catch (error) {
    return {
      message: 'Wystąpił błąd podczas wysyłania wiadomości. Spróbuj ponownie później.',
      success: false
    };
  }
}

W tym przykładzie używamy:

  1. useActionState - do zarządzania stanem formularza pomiędzy klientem a serwerem
  2. useFormStatus - do śledzenia stanu wysyłki formularza (pending)
  3. Zod - do validacji danych formularza na serwerze
  4. Komponentów funkcyjnych - do organizacji logiki UI

Popularne biblioteki do formularzy w React

Poza natywnym podejściem, istnieje kilka doskonałych bibliotek, które upraszczają pracę z formularzami w React i Next.js.

React Hook Form

React Hook Form to jedna z najpopularniejszych bibliotek do obsługi formularzy w Reakcie, która minimalizuje renderowanie i optymalizuje wydajność.

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

// Definicja schematu walidacji
const loginFormSchema = z.object({
  email: z.string().email('Nieprawidłowy adres email'),
  password: z.string().min(6, 'Hasło musi mieć co najmniej 6 znaków')
});

// Typ danych formularza inferowany ze schematu Zod
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 {
      // Symulacja opóźnienia sieciowego
      await new Promise(resolve => setTimeout(resolve, 1000));

      console.log('Login data:', data);
      // W rzeczywistej aplikacji: wywołanie API do logowania
      // 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">
          Hasło
        </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 ? 'Logowanie...' : 'Zaloguj się'}
      </button>
    </form>
  );
}

Zalety React Hook Form:

  1. Wydajność - minimalnie przerenderowuje komponenty
  2. Łatwa integracja - działa z niemodyfikowanymi elementami HTML formularza
  3. Zaawansowana walidacja - natywna integracja z Zod, Yup i innymi bibliotekami
  4. Niekonwencjonalne formy walidacji - walidacja zależna od innych pól, warunkowa walidacja, itp.

Formik

Formik to inna popularna biblioteka do formularzy w React, która oferuje bardziej deklaratywne podejście:

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

// Schemat walidacji Yup
const CheckoutSchema = Yup.object().shape({
  firstName: Yup.string().required('Imię jest wymagane'),
  lastName: Yup.string().required('Nazwisko jest wymagane'),
  email: Yup.string().email('Nieprawidłowy email').required('Email jest wymagany'),
  address: Yup.string().required('Adres jest wymagany'),
  city: Yup.string().required('Miasto jest wymagane'),
  postalCode: Yup.string()
    .matches(/^\d{2}-\d{3}$/, 'Nieprawidłowy kod pocztowy (np. 00-000)')
    .required('Kod pocztowy jest wymagany'),
  paymentMethod: Yup.string().required('Wybierz metodę płatności')
});

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

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

            // W rzeczywistej aplikacji: wywołanie API
            // await processCheckout(values);

            resetForm();
            alert('Zamówienie przyjęte!');
          } catch (error) {
            console.error('Checkout error:', error);
            alert('Wystąpił błąd podczas składania zamówienia');
          } 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">
                  Imię
                </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">
                  Nazwisko
                </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">
                Adres
              </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">
                  Miasto
                </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">
                  Kod pocztowy
                </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">
                Metoda płatności
              </label>

              <div className="space-y-2">
                <label className="flex items-center">
                  <Field type="radio" name="paymentMethod" value="card" className="mr-2" />
                  Karta płatnicza
                </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" />
                  Przelew bankowy
                </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 ? 'Przetwarzanie...' : 'Złóż zamówienie'}
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

Zalety Formik:

  1. Deklaratywny API - komponenty Form, Field, ErrorMessage
  2. Dobra dokumentacja - obszerna dokumentacja i przykłady
  3. Dojrzałość - stabilna i sprawdzona w produkcji
  4. Integracja z Yup - łatwa walidacja z bibliotekami Yup

Podsumowanie

W tym module poznaliśmy różne podejścia do tworzenia formularzy w React i Next.js:

  1. Natywne formularze React - kontrolowane komponenty z lokalnym stanem
  2. Server Actions w Next.js - nowe podejście po stronie serwera
  3. React Hook Form - wydajna biblioteka z minimalnym renderowaniem
  4. Formik - dojrzała biblioteka z deklaratywnym API

Wybór odpowiedniego podejścia zależy od specyfiki projektu:

  • Dla prostych formularzy: natywne rozwiązania React
  • Dla aplikacji Next.js: Server Actions z Progressive Enhancement
  • Dla złożonych formularzy klienckich: React Hook Form lub Formik

Niezależnie od wybranego podejścia, warto pamiętać o kilku dobrych praktykach:

  • Walidacja na wielu poziomach - klient + serwer
  • Dostępność - poprawne etykiety, atrybuty ARIA, działanie z klawiaturą
  • Informacje zwrotne - ładowanie, błędy, potwierdzenia
  • Bezpieczeństwo - zabezpieczenie przed CSRF, walidacja danych na serwerze

W następnych modułach zgłębimy bardziej zaawansowane techniki obsługi formularzy, w tym przesyłanie plików, wielokrokowe formularze i integracje z zewnętrznymi API.

Kod do tej lekcji: App.tsx
// Demo: Tworzenie formularzy w React i Next.js
// Podstawy formularzy: controlled components, eventy, submit
import React, { useState, FormEvent } from 'react';

// W React formularze działają jako "controlled components"
// Stan React kontroluje wartości pól formularza
// onChange aktualizuje stan -> React re-renderuje input z nową wartością

// Podstawowy wzorzec:
// 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(); // Zapobiegamy domyślnemu przeładowaniu strony
    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 zarządza stanem formularza
        </p>

        <form onSubmit={handleSubmit}>
          <FormInput label="Imię" 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="Temat" 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' }}>
              Priorytet
            </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',
            }}>Wiadomość</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>

        {/* Podgląd stanu React na żywo */}
        <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 (na żywo):
          </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' }}>Wysłano!</h4>
            <p style={{ color: '#b0bec5', fontSize: '0.85rem', margin: 0 }}>
              Od: {submittedData.name} ({submittedData.email})
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. W React, element <input> w formularzu jest kontrolowany, gdy:

  1. PytanieElementy formularza w React

Przydatne artykuły