Skip to main content

handle amenity change and checkbox in rent app

 

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)

amenities: [] as string[]

This means:

  • amenities is an array of strings

  • It will store selected amenities like:

["wifi", "parking", "gym"]

2️⃣ Amenities list (source of checkboxes)

const amenitiesList = ['wifi', 'parking', 'kitchen', 'tv', 'gym', 'pool', 'laundry'];

This array is used to:

  • loop

  • create one checkbox per amenity


3️⃣ Checkbox UI part (main focus)

{amenitiesList.map((amenity) => ( <div key={amenity} className="flex items-center space-x-2"> <Checkbox id={amenity} checked={formData.amenities.includes(amenity)} onCheckedChange={(checked) => handleAmenityChange(amenity, checked as boolean) } /> <Label htmlFor={amenity} className="text-sm capitalize"> {amenity === 'wifi' ? 'WIFI' : amenity} </Label> </div> ))}

🔹 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:

formData.amenities = ["wifi", "gym"];
  • wifi → ✅ checked

  • gym → ✅ checked

  • parking → ❌ unchecked

Because:

["wifi", "gym"].includes("wifi") // true

3. onCheckedChange

onCheckedChange={(checked) => handleAmenityChange(amenity, checked as boolean) }
  • Runs whenever checkbox is clicked

  • checked is:

    • true → checkbox selected

    • false → checkbox unselected

We pass:

  • amenity → "wifi"

  • checked → true / false


4️⃣ handleAmenityChange function (core logic)

const handleAmenityChange = (amenity: string, checked: boolean) => { if (checked) { setFormData(prev => ({ ...prev, amenities: [...prev.amenities, amenity] })); } else { setFormData(prev => ({ ...prev, amenities: prev.amenities.filter(a => a !== amenity) })); } };

🔹 Case 1: Checkbox is CHECKED ✅

Example: user checks wifi

checked === true

This runs:

amenities: [...prev.amenities, amenity]

If before:

amenities = ["parking"]

After:

amenities = ["parking", "wifi"]

👉 Adds amenity to array


🔹 Case 2: Checkbox is UNCHECKED ❌

Example: user unchecks wifi

checked === false

This runs:

amenities: prev.amenities.filter(a => a !== amenity)

If before:

amenities = ["wifi", "gym"]

After:

amenities = ["gym"]

👉 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 🧠

  1. User clicks checkbox

  2. onCheckedChange fires

  3. handleAmenityChange() runs

  4. If checked → add amenity

  5. If unchecked → remove amenity

  6. UI updates automatically

Comments

Popular posts from this blog

Use Ref

  in case of useref no need to deal with vdom directly real dom of browser is updated Venice That's a fantastic observation, and you're touching on the core power of  useRef . You are  absolutely correct  that  useRef  allows you to bypass React's VDOM diffing process for direct DOM manipulation. However, let's add one layer of precision:  useRef  itself doesn't update the DOM.  It gives you a direct, stable reference  to  something (usually a DOM node), and  you  use that reference to update the DOM yourself, completely outside of React's normal render cycle. Let's contrast the two flows. The  useState  Flow (The "Official" React Way) This is the "ask for permission" model. Trigger:  You call  setCount() . Render:  React schedules a re-render. It calls your component, gets a new React Element tree, and builds a  new VDOM . Reconciliation (Diffing):  React compares the new VDOM to the old...

Ternary operator and its working on mechanism on array

  If condition is true → use valueIfTrue If condition is false → use valueIfFalse ✅ Your amenity example Your code: {amenity === 'wifi' ? 'WIFI' : amenity} Breakdown: ✔ Condition: amenity === 'wifi' This checks: “Is the current amenity equal to 'wifi'?” ✔ If condition is TRUE → show: 'WIFI' ✔ If condition is FALSE → show: amenity 🎯 Example with your amenitiesList const amenitiesList = [ 'wifi' , 'parking' , 'kitchen' ]; Looping through each item: 🔹 1. amenity = "wifi" Check condition: 'wifi' === 'wifi' → TRUE So ternary returns: 'WIFI' 👉 Display: WIFI 🔹 2. amenity = "parking" Check condition: 'parking' === 'wifi' → FALSE So ternary returns: amenity // which is "parking" 👉 Display: parking 🔹 3. amenity = "kitchen" Check condition: 'kitchen' === 'wifi' → FALS...

position vs translate

  The Golden Rule 🏠 Positioning ( top , left , etc.) 👉 Moves relative to the PARENT 🚶 Translate ( translate-x , translate-y ) 👉 Moves relative to ITSELF That’s it. If you remember only this, you’ll never confuse them again. 🎯 Imagine This Real-Life Story Think of a room (parent) and a table (element) . 1️⃣ left-1/2 → Parent Based You tell someone: “Put the table so its left edge is at 50% of the room.” The room decides the position. Room Width = 1000 px 50% = 500 px Table 's left edge is placed at 500px So positioning = 📏 Room measurement 2️⃣ translate-x-1/2 → Self Based Now you say: “Move the table forward by half of its own width.” The table measures itself. Table Width = 200px 50 % = 100px It moves 100px So translate = 📦 Self measurement 🔥 Ultimate Memory Formula Positioning → Parent controls me Translate → I control myself 💡 Why Centering Needs Both When you do: left - 1 / 2 You move the left edge to center. But the e...