Rendering with map
Rendering Lists with .map()
Array.map() is a built-in JavaScript method that iterates over every element in an array, applies a callback function to each one, and returns a new array of the results without modifying the original. In React, you use it to transform an array of data objects into an array of JSX elements, which React renders into the DOM.
The syntax is: array.map((item, index) => <JSX />). The callback receives two arguments: the current item and its index in the array. You return a JSX element for each item.
Example 1: Simple String Array
JSX
function SimpleList() { const services = [ 'Web Design', 'SEO Optimization', 'Performance Marketing', 'Graphic Design', 'Content Strategy', ]; return ( <ul> {services.map((service, index) => ( {/* key is required — covered in detail in the next section */} <li key={index}>{service}</li> ))} </ul> ); } /* Output: • Web Design • SEO Optimization • Performance Marketing • Graphic Design • Content Strategy */
Example 2: Array of Objects (Recommended Pattern)
In real applications, your data is almost always an array of objects. You destructure each object in the map callback to access its properties cleanly.
JSX
function CourseList() { const courses = [ { id: 1, title: 'React Fundamentals', category: 'Frontend', level: 'Beginner' }, { id: 2, title: 'Node.js & REST APIs', category: 'Backend', level: 'Intermediate' }, { id: 3, title: 'SEO Mastery', category: 'Marketing',level: 'Beginner' }, { id: 4, title: 'UI/UX Design Principles',category: 'Design', level: 'Intermediate' }, ]; return ( <div className="course-grid"> {courses.map(({ id, title, category, level }) => ( {/* Use the unique id as key — not index */} <div key={id} className="course-card"> <h3>{title}</h3> <span>{category}</span> <span>{level}</span> </div> ))} </div> ); }
Example 3: Map Stored in a Variable (Cleaner JSX)
For complex items, compute the JSX array before the return to keep your return block clean and readable.
JSX
function TeamList({ members }) { // Build the JSX array outside the return const memberItems = members.map((member) => ( <div key={member.id} className="member-card"> <img src={member.avatar} alt={member.name} /> <h4>{member.name}</h4> <p>{member.role}</p> </div> )); // Return block is clean — just a container return ( <section className="team-grid"> <h2>Our Team</h2> {memberItems} </section> ); }
Why .map() and not .forEach()?forEach()iterates over an array but returnsundefined, it does not produce a new array.map()returns a new array of results, which is exactly what React needs: an array of JSX elements to render. Always use.map()for list rendering, not.forEach().
