← Learning Hub
Beginner

Lists and Conditions

Showing a list

Use the array map() method to turn each item into JSX. Give each item a unique key so React can track it.

Almost every app shows lists: products, messages, search results, comments. In React you keep the data in an array and use map() to turn each item into a component. Add an item to the array and React shows it; remove one and it disappears.

The key is like a roll number for each item. When the list changes, React uses keys to know which items were added, removed or moved, so it updates only those. Without keys (or with changing keys), React may mix up items - for example, keeping the wrong text in an input box.

Showing something only sometimes

Use && to show something only when a condition is true, or ? : to choose between two things.

Conditional rendering handles real situations: show a spinner while loading, an error message if something failed, "Your cart is empty" when there are no items, or an admin button only for admins. Because JSX is JavaScript, you use normal JavaScript operators to decide what to show.

Example
<!DOCTYPE html>
<html>
  <body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>

    <script type="text/babel">
      const products = [
        { id: 1, name: "Shoes", price: 1499, inStock: true },
        { id: 2, name: "Watch", price: 2999, inStock: false },
        { id: 3, name: "Bag", price: 899, inStock: true },
      ];

      function App() {
        return (
          <ul>
            {products.map(p => (
              <li key={p.id}>
                {p.name} - Rs {p.price}{" "}
                {p.inStock ? <b>In stock</b> : <i>Out of stock</i>}
                {p.price < 1000 && <span> 🔥 Budget pick</span>}
              </li>
            ))}
          </ul>
        );
      }

      ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    </script>
  </body>
</html>
▶ Try it yourself
Use a stable id from your data as the key, not the item's position, when the list can change order.
Key points
  • Use array.map() to render lists.
  • Give every list item a stable unique key.
  • Use && or ? : for conditional rendering.

📝 Test yourself

1. Which array method is used to show a list in JSX?
2. Why does each list item need a key?
3. What does {isNew && <b>New</b>} show when isNew is false?