Topic 11 of 54
Rendering Arrays with .map()
Overview
In real applications, data usually comes from APIs in the form of Arrays (e.g., an array of users, a list of products). Because you can't put a `for` loop directly inside JSX, React relies heavily on the standard JavaScript Array `.map()` method to transform an array of data into an array of JSX elements.
Syntax
The `.map()` function iterates over the `tasks` array, and for each string, it returns an `<li>` element. React then renders this array of elements automatically.
Using .map() inside JSX
jsx
function TodoList() {
const tasks = ["Buy Milk", "Clean Room", "Learn React"];
return (
<ul>
{tasks.map((task, index) => {
// Return a JSX element for every item in the array
return <li key={index}>{task}</li>;
})}
</ul>
);
}By replacing the curly braces `{}` with parentheses `()`, the arrow function implicitly returns the JSX, saving you from typing the `return` keyword.
Implicit Return syntax
jsx
// Cleaner syntax using arrow functions with implicit return (parentheses instead of braces)
function ProductList({ products }) {
return (
<div className="grid">
{products.map(product => (
<div key={product.id} className="card">
<h3>{product.name}</h3>
<p>${product.price}</p>
</div>
))}
</div>
);
}Common Pitfalls
- Using curly braces `{}` in an arrow function but forgetting the `return` keyword. This results in nothing rendering on the screen.
- Forgetting to provide a unique `key` prop to the outermost element returned by the `.map()` function.
Interview Tips
- Be prepared to explain why `.map()` is used instead of `.forEach()`. (Answer: `.map()` returns a *new array* of JSX elements, which React can render. `.forEach()` returns `undefined`).
Real-World Example
Rendering a list of objects fetched from an API.
example
jsx
function UserDirectory({ users }) {
// users is an array of objects: [{id: 1, name: 'Alice', role: 'Admin'}, ...]
return (
<div className="user-list">
{users.map(user => (
<UserCard
key={user.id}
name={user.name}
role={user.role}
/>
))}
</div>
);
}