React Tutorial menu

React Lists and Keys

To show a list of items in React, you turn an array of data into an array of JSX elements with map().

Rendering a List with map()

Example

jsx
function CityList() {
  const cities = ["Karachi", "Lahore", "Islamabad", "Peshawar"];

  return (
    <ul>
      {cities.map((city) => (
        <li key={city}>{city}</li>
      ))}
    </ul>
  );
}
Output
• Karachi
• Lahore
• Islamabad
• Peshawar

map() runs the arrow function once for each city and returns a new array of <li> elements. React shows them all.

Why Keys Are Needed

Every item in a list needs a key prop. A key is a value that is unique among its siblings and stays the same between renders.

React uses keys to know which item is which. When you add, remove or sort items, keys let React update only the changed ones instead of rebuilding the whole list.

If you forget the key, React shows a warning in the console:

Example

text
Warning: Each child in a list should have a unique "key" prop.

Lists of Objects

Real data usually comes as an array of objects, each with an id. Use the id as the key.

Example

jsx
const products = [
  { id: 1, name: "USB Cable", price: 350 },
  { id: 2, name: "Power Bank", price: 3200 },
  { id: 3, name: "Earphones", price: 950 },
];

function ProductTable() {
  return (
    <table>
      <tbody>
        {products.map((p) => (
          <tr key={p.id}>
            <td>{p.name}</td>
            <td>Rs {p.price}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
Output
USB Cable     Rs 350
Power Bank    Rs 3200
Earphones     Rs 950

Rules for Keys

RuleWhy
Keys must be unique among siblingsTwo items with the same key confuse React
Keys must not change between rendersA new key makes React rebuild the item
Use an id from your dataIt is stable and unique
Avoid the array index if the list can changeIndexes shift when items are added or removed
Put the key on the outer element inside map()Not inside the child component

The array index (map((item, index) => ...)) is acceptable only for lists that never change order.

Rendering a Component for Each Item

Usually you render a component for each item and pass the data as props:

Example

jsx
function ProductCard({ name, price }) {
  return (
    <div className="card">
      <h3>{name}</h3>
      <p>Rs {price}</p>
    </div>
  );
}

function ProductGrid() {
  return (
    <div className="grid">
      {products.map((p) => (
        <ProductCard key={p.id} name={p.name} price={p.price} />
      ))}
    </div>
  );
}

Note that key is placed on <ProductCard>, but the component cannot read it as a prop. If the component needs the id, pass it again as a separate prop like id={p.id}.

Filtering a List

Use filter() before map() to show only some items.

Example

jsx
function CheapProducts() {
  const cheap = products.filter((p) => p.price < 1000);

  return (
    <ul>
      {cheap.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}
Output
• USB Cable
• Earphones

When a list may be empty, show a friendly message: {items.length === 0 && <p>No products found.</p>}.

Exercise

Exercise

What is the best value to use as a key for a list of students from a database?

Learn React with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp