Lists and Keys
Rendering arrays with .map(), the key prop, filtering, and sorting
Skills taught: react.list-rendering, react.key-prop, react.array-map, react.list-filtering
Rendering lists with .map()
const PRODUCTS = [
{ id: 1, name: 'React Handbook', category: 'Books', price: 499, inStock: true },
{ id: 2, name: 'TypeScript Pro', category: 'Books', price: 599, inStock: false },
{ id: 3, name: 'USB-C Hub', category: 'Electronics', price: 999, inStock: true },
{ id: 4, name: 'Desk Lamp', category: 'Accessories', price: 349, inStock: true },
];
function ProductItem({ id, name, category, price, inStock }) {
return (
<li style={{
padding: '10px', borderBottom: '1px solid #e5e7eb',
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
opacity: inStock ? 1 : 0.5
}}>
<div>
<strong>{name}</strong>
<span style={{ marginLeft: '8px', fontSize: '0.78rem', color: '#6b7280' }}>{category}</span>
</div>
<div style={{ textAlign: 'right' }}>
<div>₹{price}</div>
{!inStock && <small style={{ color: '#ef4444' }}>Out of stock</small>}
</div>
</li>
);
}
function App() {
const [filter, setFilter] = useState('all');
// Filter — create new array, don't mutate PRODUCTS
const visible = filter === 'inStock'
? PRODUCTS.filter(p => p.inStock)
: PRODUCTS;
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', maxWidth: '420px' }}>
<div style={{ marginBottom: '8px', display: 'flex', gap: '8px' }}>
<button onClick={() => setFilter('all')} style={{ fontWeight: filter === 'all' ? 'bold' : 'normal' }}>All</button>
<button onClick={() => setFilter('inStock')} style={{ fontWeight: filter === 'inStock' ? 'bold' : 'normal' }}>In Stock</button>
</div>
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
{visible.map(product => (
<ProductItem key={product.id} {...product} /> /* key must be here, on the outermost element */
))}
</ul>
<p style={{ fontSize: '0.8rem', color: '#6b7280' }}>{visible.length} items</p>
</div>
);
}
Frequently Asked Questions
Can I use the array index as a key?
Yes, but only if: (1) the list is static and never reordered or filtered, and (2) no list item has local state that needs to persist. For all other cases — dynamic lists, filtered lists, drag-to-reorder — use a stable unique ID from the data.