Objects - Guided Practice
๐๏ธ Dynamic Product Display
In this hands-on practice, we'll explore how to dynamically display products on a webpage.
๐งช Exercise Steps
๐ฆ Step 1: Display Products
๐ฏ Task: Create a product object in the array of products with the following structure:
- id: unique identifier (e.g., 1)
- title: name of the product (e.g., "Maple Leaf T-Shirt")
- basePrice: base price of the product (e.g., 7.99)
- materials: an object with material types and their prices
- e.g., materials = { "cotton": 7.99, "polyester": 8.99, "blend": 9.49 }
- image: path to the product image (e.g., "images/blue-t-shirt-maple-leaf.webp")
๐ Task: Select the container element where product cards will be rendered:
// Set 'productsContainer' to the HTML element with the id 'products'
๐ ๏ธ Task: Write a function to create HTML for each product using template literals:
// Define a function 'displayProducts':
// - Create an empty array called 'htmlTemplate'
// - Loop through each 'product':
// - Build an HTML-like string using template literals, and push it into the htmlTemplate array:
// - Include a container div with styling classes
// - Add an image using product.image and product.title
// - Include a heading with product.title
// - Display the base price
// - Add a call-to-action button
// - Combine the list into one string and insert into 'productsContainer'
// - Call 'displayProducts()' to render it
๐ง Why This Matters: Dynamically generating HTML from objects allows you to scale easily โ change the data, and the UI updates automatically!
๐งต Step 2: Refactor to Show Dynamic Material Options
Understanding how to work with dynamic object properties is crucial for building flexible UIs. Youโll use Object.entries() to handle unknown material types.
๐งฉ Task: Loop through product.materials using Object.entries() to generate <option> tags for each material:
// Modify the 'displayProducts' function:
// - For each 'product':
// - Locate the <select> element
// - Use Object.entries(product.materials) to get all material-price pairs
// - Loop through them and add <option value="material">Material - $price</option>
// - Close the select, add remaining product info and push to 'htmlTemplate'
// - Set 'productsContainer.innerHTML' to htmlTemplate.join('')
๐ง Why This Approach?: With Object.entries(), your code automatically adapts to the structure of the data โ no hardcoding, no surprises. You build smarter, not harder ๐ก