| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19⚡ | 20 |
Goal: Display the fetched meals using a for loop.
User Story: As a user, I want to see the meals displayed on the page so that I can view what’s planned for the potluck.
Add display logic using a for loop to render each meal in the list.
mealsDisplay array<li> element with the meal information{mealsDisplay} in the JSXNeed help with the display loop? Check out these snippets:
const mealsDisplay = []
for (let i = 0; i < meals.length; i++) {
mealsDisplay.push(
<li key={meals[i].id}>
{meals[i].meal_name} by {meals[i].guest_name} serves {meals[i].serves} ( {meals[i].kind_of_dish} )
</li>
)
}
<ul>
{mealsDisplay}
</ul>
Why do we need the key prop?
id) rather than array indexUnderstanding JSX in loops:
mealsDisplay.push(
<li key={meals[i].id}>
{meals[i].meal_name} by {meals[i].guest_name} serves {meals[i].serves} ( {meals[i].kind_of_dish} )
</li>
)
{variable} to insert JavaScript values into JSXAlternative approaches:
You could also use .map() instead of a for loop:
const mealsDisplay = meals.map(meal => (
<li key={meal.id}>
{meal.meal_name} by {meal.guest_name} serves {meal.serves} ({meal.kind_of_dish})
</li>
));
📺 Learn More: