Introduction
The map function helps you create a list of elements from an array easily. It saves time and keeps your code clean.
The map function helps you create a list of elements from an array easily. It saves time and keeps your code clean.
array.map(item => <Component key={item.id} prop={item.value} />)const numbers = [1, 2, 3]; const listItems = numbers.map(num => <li key={num}>{num}</li>);
const names = ['Anna', 'Bob', 'Cara']; const nameList = names.map((name, index) => <p key={index}>Hello, {name}!</p>);
This React component shows a list of fruits using map. Each fruit becomes a list item with a unique key.
import React from 'react'; export default function FruitList() { const fruits = ['Apple', 'Banana', 'Cherry']; return ( <ul> {fruits.map((fruit, idx) => ( <li key={idx}>{fruit}</li> ))} </ul> ); }
Keys help React update only changed items, improving performance.
Never use random numbers or Math.random() as keys because keys must be stable.
Map does not change the original array; it creates a new one.
Use map to turn arrays into lists of React elements.
Always provide a unique key prop for each element inside map.
Map keeps your UI code simple and easy to read.
map function in React when rendering lists?map does in JavaScriptmap function creates a new array by applying a function to each element of the original array without changing it.map is used to convert each item in an array into a React element, which can then be rendered as a list.map inside a React component to render a list of names stored in const names = ['Anna', 'Bob', 'Cara']?map and JSXmap with an arrow function returning JSX elements is correct. The element must have a unique key prop inside the returned JSX.{names.map(name => <li key={name}>{name}</li>)} correctly uses map, returns a list item with curly braces around name, and includes a unique key prop.const numbers = [1, 2, 3];
const listItems = numbers.map(n => <li key={n}>Number: {n * 2}</li>);
return <ul>{listItems}</ul>;map:const items = ['a', 'b', 'c'];
return <ul>{items.map(item => <li>{item}</li>)};map function returns key prop, which React requires for lists.item are correct, map is valid inside JSX, and array can contain strings.const users = [
{ id: 1, name: 'Alice', hobbies: ['Reading', 'Hiking'] },
{ id: 2, name: 'Bob', hobbies: ['Cooking'] }
];
// Which code correctly renders a list of users with their hobbies?div uses user.id as key, which is unique. The inner li uses hobby as key, which is unique per hobby.{users.map(user => <div key={user.id}><h3>{user.name}</h3><ul>{user.hobbies.map(hobby => <li key={hobby}>{hobby}</li>)} correctly nests the hobbies list inside each user and assigns proper keys. Other options miss keys or reuse keys incorrectly.Pass the test and this pattern moves unknown