
กำลังโหลด...

กำลังโหลด...

ฟอร์มพร้อมแล้ว! ตอนนี้พี่อยากให้กด Submit แล้วเช็คว่ากรอกครบทุกช่องไหม ถ้าครบก็โชว์ข้อมูลที่กรอกให้ดูด้วย
เป้าหมายของ Mission นี้: เพิ่มการ validate เบื้องต้นและแสดงข้อมูลที่กรอกหลัง Submit
flowchart TD
A["กด Submit"] --> B["e.preventDefault()"]
B --> C{"กรอกครบทุกช่องไหม?"}
C -->|"ไม่ครบ"| D["โชว์ error"]
C -->|"ครบ"| E["โชว์ข้อมูลที่กรอก"]
"use client";
import { useState } from "react";
export function SignupForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [submitted, setSubmitted] = useState(false);
function handleSubmit(e: React.FormEvent) {
e.preventDefault(); // กันไม่ให้หน้าเว็บ reload เวลากด submit ฟอร์ม
if (!name || !email || !phone || !password) {
setError("กรอกให้ครบทุกช่องก่อนนะ");
setSubmitted(false);
return;
}
setError("");
setSubmitted(true);
}
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-3">
{/* ... input เดิมจาก Mission ก่อนหน้า ... */}
{error && <p className="text-red-600">{error}</p>}
<button type="submit">สมัครสมาชิก</button>
{submitted && (
<div className="rounded-lg border p-4">
<p>ชื่อ: {name}</p>
<p>อีเมล: {email}</p>
<p>เบอร์โทร: {phone}</p>
</div>
)}
</form>
);
}
สังเกต:
e.preventDefault()สำคัญมาก — ถ้าลืม เบราว์เซอร์จะ reload หน้าทั้งหน้าทันทีที่กด submit ทำให้ state ที่เก็บไว้หายหมด
ลองต่อยอดเอง เช่น เช็ครูปแบบอีเมลให้ละเอียดขึ้น หรือเช็คความยาวรหัสผ่านขั้นต่ำ — Chapter นี้จบ แล้ว ไปเรียน Fetch API กันต่อ