In any real-world application, data is often fetched from a database and delivered as an array of objects. List Rendering in React is the process of converting these arrays into a set of interactive components or JSX elements.
The primary method for list rendering is using the standard JavaScript map() array method directly inside JSX.
1. The map() Method in JSX
The map() method iterates over an array, calls a provided callback function for every element, and returns a new array containing the results of those function calls.
When used inside JSX:
- The callback function receives one element (e.g., a
userobject) during each iteration. - The callback function must return a single JSX element (e.g., a
<li>or a<UserCard />). - The final result is an array of JSX elements that React efficiently renders to the screen.
2. The Importance of the key Prop
When rendering lists, React requires every top-level element in the returned array to have a special, stable attribute called key.
- What it does: The
keyprop gives React a unique identifier for each list item. This helps React efficiently update, insert, or remove items when the data changes, minimizing manipulation of the actual DOM and ensuring fast performance. - What it should be: The key must be unique among sibling elements. It should ideally be a stable ID from your data (e.g., a database ID). Using the array index (
index) is acceptable only if the list items will never be reordered, added, or removed.
Execution Example: Rendering a List of Items
In your my-first-app/src directory:
- Open the main file,
App.js. - Replace its content with the following code:
import React from 'react';
const products = [
{ id: 101, name: "Wireless Earbuds", price: 79.99 },
{ id: 102, name: "Portable Speaker", price: 129.50 },
{ id: 103, name: "Smart Watch", price: 299.00 }
];
function ProductList() {
// Use the map() method on the products array
const listItems = products.map(product => (
// 1. The top-level JSX element (<li>) must have a unique 'key'.
// We use product.id because it is a stable, unique identifier.
<li key={product.id}>
{product.name} - <strong>${product.price.toFixed(2)}</strong>
</li>
));
return (
<div className="ListDemo">
<h2>Products for Sale</h2>
<ul>
{/* 2. Insert the array of list items into the JSX */}
{listItems}
</ul>
</div>
);
}
export default ProductList;
- Local Execution: Run
npm startin your terminal. - Observation: The three objects in the
productsarray are transformed into three separate<li>elements in the browser.
3. Rendering Custom Components in a List
In complex applications, it is best practice to move the rendering logic for each item into its own component. The parent component (ProductList) handles the mapping, and the child component (ProductItem) handles the display.
Execution Example: Component List
We will create two files:
ProductItem.js(Child Component)App.js(Parent Component – mapping the data)
A. ProductItem.js (Child Component)
Create a new file ProductItem.js:
import React from 'react';
function ProductItem({ name, price }) {
return (
<div style={{ padding: '10px', borderBottom: '1px dotted #ccc' }}>
<h4>{name}</h4>
<p>Price: ${price.toFixed(2)}</p>
</div>
);
}
export default ProductItem;
B. App.js (Parent Component)
Modify App.js to use the new component:
import React from 'react';
import ProductItem from './ProductItem'; // Import the child component
const products = [
{ id: 101, name: "Wireless Earbuds", price: 79.99 },
{ id: 102, name: "Portable Speaker", price: 129.50 },
{ id: 103, name: "Smart Watch", price: 299.00 }
];
function App() {
return (
<div className="ComponentListDemo">
<h2>Product Catalogue</h2>
{products.map(product => (
// The key must be on the custom component tag.
<ProductItem
key={product.id}
name={product.name}
price={product.price}
// The key prop is special and NOT accessible inside ProductItem.js props.
/>
))}
</div>
);
}
export default App;
This pattern is the standard, scalable way to build complex, data-driven interfaces in React.
