Rendering Lists in React

Why Lists?

  • Often, you want to display multiple items: like a list of users, posts, products, etc.

  • React lets you render lists by mapping over arrays and outputting JSX elements.


Basic Example: Rendering a List of Names

jsx
function NameList() {
const names = ['Alice', 'Bob', 'Charlie'];

return (
<ul>
{names.map((name, index) => (
<li key={index}>{name}</li>
))}
</ul>
);
}

  • .map() goes through each item in the names array.

  • For each name, it returns a <li> element.

  • Important: Each list item needs a unique key prop (here we use the index).


Why is the key Prop Important?

  • React uses key to identify which items changed, added, or removed.

  • Helps React optimize rendering performance.

  • Keys must be unique among siblings, but don’t need to be globally unique.


Better Key Usage

Avoid using array index as keys if items can be reordered or changed. Use unique IDs if available:

jsx
const users = [
{ id: 101, name: 'Alice' },
{ id: 102, name: 'Bob' },
{ id: 103, name: 'Charlie' },
];

function UserList() {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}


Rendering Complex Lists

You can render more complex structures, including multiple elements per item:

jsx
function PostList({ posts }) {
return (
<div>
{posts.map(post => (
<div key={post.id} className="post">
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
);
}

Summary

  • Use .map() to render arrays as lists of JSX elements.

  • Always include a unique key prop on list items.

  • Use stable IDs for keys when possible to avoid rendering issues.

Leave a Reply

Your email address will not be published. Required fields are marked *