Menu

Rendering Lists in React: map(), Keys & Examples

Rendering Lists and Using Keys

How Do You Render a List?

With the JavaScript map() method. It transforms an array of data into an array of JSX elements.

Syntax

jsx

{items.map(item => <li key={item.id}>{item.name}</li>)}

Example

src/components/CourseList.jsx

jsx

import CourseCard from "./CourseCard";

function CourseList() {

const courses = [

{ id: 1, title: "React Fundamentals", lessons: 12, progress: 65 },

{ id: 2, title: "Node.js Basics", lessons: 18, progress: 20 },

{ id: 3, title: "MongoDB Essentials", lessons: 9, progress: 100 }

];

return (

<div>

<h2>My Courses ({courses.length})</h2>

{courses.map(course => (

<CourseCard

key={course.id}

title={course.title}

lessons={course.lessons}

progress={course.progress}

/>

))}

</div>

);

}

export default CourseList;

How It Works

  • courses.map(...) returns an array of <CourseCard /> elements. React knows how to render an array of elements.
  • Each card gets its data as props from the current array item.
  • key={course.id} gives React a stable identifier for each item.

What Are Keys and Why Do They Matter?

When the list changes, React needs to know which item is which. A key is a unique, stable identifier that tells React "this element is the same one as before".

Without keys, React warns you in the console and may re-render items incorrectly — a common symptom is text typed into one row's input jumping to another row after the list reorders.

Key rules:

Do

Do not

Use a unique ID from your data (course.id)Use the array index if the list can reorder or change
Keep keys stable across rendersUse Math.random() this breaks React entirely
Put the key on the outermost element inside map()Put the key on a child element inside the returned JSX

Using the array index as a key (courses.map((course, index) => ... key={index})) is acceptable only when the list never reorders, never has items inserted in the middle, and never has items removed. In practice, use a real ID.

Filtering Before Rendering

Combine filter() with map() for search and filter features:

jsx

const [search, setSearch] = useState("");

const visibleCourses = courses.filter(course =>

course.title.toLowerCase().includes(search.toLowerCase())

);

return (

<div>

<input value={search} onChange={e => setSearch(e.target.value)} />

{visibleCourses.length === 0 ? (

<p>No courses match your search.</p>

) : (

visibleCourses.map(course => <CourseCard key={course.id} {...course} />)

)}

</div>

);

Note {...course} — this spreads every property of the object as a separate prop. It is a convenient shortcut when the prop names match the object keys.

Output

Three course cards, and a search box that narrows the list as you type.


ReactJS Tutorial



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details