I’ll explain only the Checkbox part and handleAmenityChange step-by-step in a simple + beginner-friendly way.
1️⃣ Amenities state (important to understand first)
This means:
-
amenitiesis an array of strings -
It will store selected amenities like:
2️⃣ Amenities list (source of checkboxes)
This array is used to:
-
loop
-
create one checkbox per amenity
3️⃣ Checkbox UI part (main focus)
🔹 What is happening here?
1. .map() creates multiple checkboxes
For each item in amenitiesList, a checkbox is created.
Example:
-
wifi → checkbox
-
parking → checkbox
-
gym → checkbox
2. checked={formData.amenities.includes(amenity)}
This line decides:
👉 Is the checkbox checked or not?
Example:
-
wifi → ✅ checked
-
gym → ✅ checked
-
parking → ❌ unchecked
Because:
3. onCheckedChange
-
Runs whenever checkbox is clicked
-
checkedis:-
true→ checkbox selected -
false→ checkbox unselected
-
We pass:
-
amenity→"wifi" -
checked→true / false
4️⃣ handleAmenityChange function (core logic)
🔹 Case 1: Checkbox is CHECKED ✅
Example: user checks wifi
This runs:
If before:
After:
👉 Adds amenity to array
🔹 Case 2: Checkbox is UNCHECKED ❌
Example: user unchecks wifi
This runs:
If before:
After:
👉 Removes amenity from array
5️⃣ Why this approach is GOOD ✅
✔ Controlled component
✔ React state is always source of truth
✔ Easy to send amenities to backend
✔ No duplicate values
✔ Beginner + production friendly
6️⃣ Final flow in simple words 🧠
-
User clicks checkbox
-
onCheckedChangefires -
handleAmenityChange()runs -
If checked → add amenity
-
If unchecked → remove amenity
-
UI updates automatically
Comments
Post a Comment