React 4

 

Chapter 4 — Rendering Lists with map()

🎯 Goal

Learn how to display many items using one component and one loop instead of writing the same code repeatedly.


First, one new idea (2 minutes)

Imagine you're writing the names of 100 students on certificates.

❌ Bad idea:

Rahul
Amit
Sara
Priya
...

(write each one manually)

✅ Better idea:

For every student,
print the student's name.

React works the same way.

Instead of writing:

<ProductCard name="iPhone" />
<ProductCard name="MacBook" />
<ProductCard name="AirPods" />

We usually store the data:

const products = [
  "iPhone",
  "MacBook",
  "AirPods"
];

Then generate the UI automatically.


New Syntax

const products = ["iPhone", "MacBook", "AirPods"];

products.map((product) => (
  <p>{product}</p>
));

What is map()?

Think of it like a photocopy machine.

Input:

Apple
Banana
Orange

Machine:

Wrap every fruit inside <p>

Output:

<p>Apple</p>
<p>Banana</p>
<p>Orange</p>

New Syntax Explained

products.map((product) => ...)
  • products → the array

  • .map() → visit every item

  • product → the current item

You can choose any name:

products.map((item) => ...)

or

products.map((fruit) => ...)

The name doesn't matter.


MCQs

Q1

Why do we use map() in React?

(A) To style components

(B) To display multiple items from an array

(C) To create folders

(D) To install packages


Answer: (B)

Mini Explanation

map() lets us generate UI for every item in an array.


Q2

Given:

const fruits = ["Apple", "Banana"];

Which code displays both fruits?

(A)

fruits.map((fruit) => <p>{fruit}</p>)

(B)

fruit.map((fruits) => <p>{fruit}</p>)

(C)

map(fruits)

(D)

<p>{fruits}</p>

Answer: (A)

Mini Explanation

Call map() on the array.


Q3

Predict the output.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruits.map((fruit) => (
        <p>{fruit}</p>
      ))}
    </>
  );
}

(A) Apple Banana

(B) Apple

(C) Banana

(D) Error


Answer: (A)


Q4

How many <p> elements are created?

const colors = ["Red", "Blue", "Green"];
colors.map((color) => (
  <p>{color}</p>
));

(A) 1

(B) 2

(C) 3

(D) 4


Answer: (C)

Mini Explanation

One <p> is created for each item.


Q5

Predict the output.

const numbers = [10, 20];
numbers.map((number) => (
  <h1>{number}</h1>
));

(A) 10 20

(B) 1020

(C) Error

(D) Blank page


Answer: (A)


Q6

Find the bug.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruit.map((fruit) => (
        <p>{fruit}</p>
      ))}
    </>
  );
}

(A) No bug

(B) Should use fruits.map(...)

(C) Missing return

(D) Missing export


Answer: (B)

Mini Explanation

The array is called fruits, not fruit.


Q7

Which variable represents the current item?

products.map((product) => ...)

(A) products

(B) map

(C) product

(D) None


Answer: (C)

Mini Explanation

product is the current item being processed.


Q8

Which code is better?

Option A

<ProductCard name="iPhone" />
<ProductCard name="MacBook" />
<ProductCard name="AirPods" />

Option B

products.map((product) => (
  <ProductCard name={product} />
))

(A) Option A

(B) Option B

(C) Both are equally good

(D) Neither


Answer: (B)

Mini Explanation

It scales easily. Add a new product to the array, and the UI updates automatically.


Q9

Predict the output.

const animals = ["Dog"];
animals.map((animal) => (
  <h2>{animal}</h2>
));

(A) Dog

(B) Dogs

(C) Error

(D) Nothing


Answer: (A)


Q10

Find the bug.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruits.map((item) => (
        <p>{items}</p>
      ))}
    </>
  );
}

(A) No bug

(B) Should use {item}

(C) Missing export

(D) Missing map()


Answer: (B)

Mini Explanation

You named the variable item but tried to use items.

Names must match.


Q11

Predict the output.

const cities = ["Delhi", "Mumbai", "Pune"];
cities.map((city) => (
  <h3>{city}</h3>
));

(A) Delhi Mumbai Pune

(B) Delhi

(C) Pune

(D) Error


Answer: (A)


Q12

Which statement is true?

(A) map() only works with numbers.

(B) map() works with arrays.

(C) map() only works in Next.js.

(D) map() creates CSS.


Answer: (B)


Q13

Predict the output.

const names = [];
names.map((name) => (
  <p>{name}</p>
));

(A) Error

(B) Blank output

(C) undefined

(D) One empty paragraph


Answer: (B)

Mini Explanation

The array is empty, so there are no items to render.


Q14

Which is easier to maintain?

(A) Writing 100 <ProductCard /> components manually

(B) Storing products in an array and using map()

(C) Copying HTML repeatedly

(D) Creating one file per product


Answer: (B)


Q15

Predict the output.

const scores = [90, 80, 70];
scores.map((score) => (
  <p>{score}</p>
));

(A) 90 80 70

(B) 90

(C) Error

(D) Blank page


Answer: (A)


Q16

Interview Trap 🚨

Which code will produce a warning in React?

(A)

products.map((product) => (
  <p>{product}</p>
))

(B)

products.map((product) => (
  <p key={product}>{product}</p>
))

(C) Both

(D) Neither


Answer: (A)

Mini Explanation

When rendering a list, React expects a special prop called key.

Without it, you'll see a warning like:

"Each child in a list should have a unique 'key' prop."

For now, remember this rule:

Whenever you use map() to render a list, add a key.

Example:

products.map((product) => (
  <p key={product}>{product}</p>
));

We'll learn why React needs key in a later chapter.


Q17

Predict the output.

const books = ["Clean Code", "Deep Work"];
books.map((book) => (
  <h2>{book}</h2>
));

(A) Clean Code Deep Work

(B) Deep Work Clean Code

(C) Error

(D) One heading


Answer: (A)


Q18 (Hard)

You're building an e-commerce website with 5,000 products.

Which approach is better?

(A) Write 5,000 ProductCard components manually.

(B) Store the products in an array and use map().

(C) Create 5,000 pages with repeated HTML.

(D) Copy and paste each product.


Answer: (B)

Mini Explanation

This is exactly how real-world apps work. Product data comes from a database or API, and map() renders each item automatically.


⭐ Chapter Summary (The 20% You'll Use Every Day)

Remember these five patterns:

1. Store your data in an array.

const fruits = ["Apple", "Banana"];

2. Use map() to visit every item.

fruits.map((fruit) => ...)

3. Render JSX for each item.

fruits.map((fruit) => (
  <p>{fruit}</p>
));

4. Use {} to insert JavaScript values.

<p>{fruit}</p>

5. Add a key when rendering lists.

fruits.map((fruit) => (
  <p key={fruit}>{fruit}</p>
));

For now, just remember: List = map() + key.


🎯 Mini Coding Challenge

Create an array:

const skills = [
  "HTML",
  "CSS",
  "JavaScript",
  "React",
  "Next.js"
];

Display all the skills using map().

Bonus: Add a key to each rendered item.


🚀 Mini Real-World Project

Product Catalog

Create an array like this:

const products = [
  { name: "iPhone 16", price: "$999" },
  { name: "MacBook Air", price: "$1199" },
  { name: "AirPods Pro", price: "$249" }
];

Create a reusable ProductCard component that accepts:

  • name

  • price

Then use map() to render all the products.

Rule: Don't manually write three ProductCard components. Generate them from the array.


💡 One Important Note

This chapter introduced arrays, map(), and a small preview of key because these are among the most frequently used patterns in React.

In the next chapter, we'll combine what you've learned with Conditional Rendering—showing or hiding UI based on conditions (for example, "Show 'Out of Stock' only when a product isn't available"). This pattern appears in almost every production Next.js application.

Reply "ok" when you're ready for Chapter 5: Conditional Rendering.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.