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
-
.map()goes through each item in thenamesarray. -
For each
name, it returns a<li>element. -
Important: Each list item needs a unique
keyprop (here we use theindex).
Why is the key Prop Important?
-
React uses
keyto 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:
Rendering Complex Lists
You can render more complex structures, including multiple elements per item:
Summary
-
Use
.map()to render arrays as lists of JSX elements. -
Always include a unique
keyprop on list items. -
Use stable IDs for keys when possible to avoid rendering issues.
