React js Shopping Cart Practice Questions with Solutions

Introduction

A Shopping Cart is a practical React project that helps you understand how real e-commerce interfaces work. It combines components, props, state, arrays, events, conditional rendering, and calculations. In this chapter, we will build shopping cart features step by step, including displaying products, adding products to the cart, updating quantities, removing items, calculating totals, and creating a complete cart application. React js Shopping Cart Practice questions with solutions to help you understand the concepts.

1. How to Display Products in a React Shopping Cart?

Problem Statement:
Create a React component that displays a list of products with their names and prices.

React Solution:

function ShoppingCart() {
  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Headphones", price: 3000 },
    { id: 3, name: "Keyboard", price: 1500 }
  ];

  return (
    <div>
      <h1>Products</h1>

      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

export default ShoppingCart;

Output:

Products

Laptop
₹60000

Headphones
₹3000

Keyboard
₹1500

Explanation:
Products are stored in an array of objects and rendered using map(). Each product has a stable unique id, which is used as the React list key.

Concepts Covered:

  • Arrays
  • Objects
  • map()
  • List Keys
  • JSX

2. How to Add a Product to the Shopping Cart?

Problem Statement:
Create a product list with an Add to Cart button and add the selected product to the cart.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Headphones", price: 3000 },
    { id: 3, name: "Keyboard", price: 1500 }
  ];

  const [cart, setCart] = useState([]);

  function addToCart(product) {
    setCart((currentCart) => [
      ...currentCart,
      product
    ]);
  }

  return (
    <div>
      <h1>Products</h1>

      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>₹{product.price}</p>

          <button onClick={() => addToCart(product)}>
            Add to Cart
          </button>
        </div>
      ))}

      <h2>Cart Items: {cart.length}</h2>
    </div>
  );
}

export default ShoppingCart;

Output:

Products

Laptop
₹60000
[Add to Cart]

Headphones
₹3000
[Add to Cart]

Keyboard
₹1500
[Add to Cart]

Cart Items: 0

After adding a laptop:

Cart Items: 1

Explanation:
The cart array is stored in state. When the user clicks Add to Cart, the selected product is added using the spread operator.

This is a basic implementation. If the same product is added multiple times, it will currently create multiple cart entries. The next questions improve this behavior.

Concepts Covered:

  • useState
  • Event Handling
  • Array State
  • Spread Operator
  • Props/Data Passing

3. How to Prevent Duplicate Products in a Shopping Cart?

Problem Statement:
If a product is already in the cart, increase its quantity instead of adding another separate cart item.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Headphones", price: 3000 }
  ];

  const [cart, setCart] = useState([]);

  function addToCart(product) {
    setCart((currentCart) => {
      const existingProduct = currentCart.find(
        (item) => item.id === product.id
      );

      if (existingProduct) {
        return currentCart.map((item) =>
          item.id === product.id
            ? { ...item, quantity: item.quantity + 1 }
            : item
        );
      }

      return [
        ...currentCart,
        { ...product, quantity: 1 }
      ];
    });
  }

  return (
    <div>
      <h1>Products</h1>

      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>₹{product.price}</p>

          <button onClick={() => addToCart(product)}>
            Add to Cart
          </button>
        </div>
      ))}

      <h2>Cart</h2>

      {cart.map((item) => (
        <p key={item.id}>
          {item.name} - Quantity: {item.quantity}
        </p>
      ))}
    </div>
  );
}

export default ShoppingCart;

Output:

Products

Laptop
₹60000
[Add to Cart]

Headphones
₹3000
[Add to Cart]

Cart

Laptop - Quantity: 1

After clicking Add to Cart for Laptop again:

Laptop - Quantity: 2

Explanation:
find() checks whether the product already exists. If it does, map() creates a new cart array and increases its quantity. Otherwise, the product is added with quantity: 1.

Concepts Covered:

  • find()
  • map()
  • Conditional Logic
  • Object Spread
  • Immutable State Updates

4. How to Increase and Decrease Product Quantity?

Problem Statement:
Add + and - buttons to change the quantity of products already in the cart.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const [cart, setCart] = useState([
    {
      id: 1,
      name: "Laptop",
      price: 60000,
      quantity: 1
    }
  ]);

  function increaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id
          ? { ...item, quantity: item.quantity + 1 }
          : item
      )
    );
  }

  function decreaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id && item.quantity > 1
          ? { ...item, quantity: item.quantity - 1 }
          : item
      )
    );
  }

  return (
    <div>
      <h1>Shopping Cart</h1>

      {cart.map((item) => (
        <div key={item.id}>
          <h3>{item.name}</h3>
          <p>₹{item.price}</p>

          <button onClick={() => decreaseQuantity(item.id)}>
            -
          </button>

          <span> {item.quantity} </span>

          <button onClick={() => increaseQuantity(item.id)}>
            +
          </button>
        </div>
      ))}
    </div>
  );
}

export default ShoppingCart;

Output:

Shopping Cart

Laptop
₹60000

[-] 1 [+]

After clicking +:

[-] 2 [+]

After clicking -:

[-] 1 [+]

Explanation:
map() updates only the selected product. The example prevents the quantity from going below 1.

Concepts Covered:

  • map()
  • State Updates
  • Event Handling
  • Conditional Logic
  • Immutable Updates

5. How to Remove a Product from the Shopping Cart?

Problem Statement:
Add a Remove button that completely removes a product from the cart.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const [cart, setCart] = useState([
    { id: 1, name: "Laptop", price: 60000, quantity: 1 },
    { id: 2, name: "Mouse", price: 1000, quantity: 2 }
  ]);

  function removeFromCart(id) {
    setCart((currentCart) =>
      currentCart.filter((item) => item.id !== id)
    );
  }

  return (
    <div>
      <h1>Shopping Cart</h1>

      {cart.map((item) => (
        <div key={item.id}>
          <p>
            {item.name} - Quantity: {item.quantity}
          </p>

          <button onClick={() => removeFromCart(item.id)}>
            Remove
          </button>
        </div>
      ))}
    </div>
  );
}

export default ShoppingCart;

Output:

Shopping Cart

Laptop - Quantity: 1
[Remove]

Mouse - Quantity: 2
[Remove]

After removing Mouse:

Shopping Cart

Laptop - Quantity: 1
[Remove]

Explanation:
filter() creates a new array containing every product except the one whose ID matches the selected item.

Concepts Covered:

  • filter()
  • Array State
  • Event Handling
  • Immutable Updates

6. How to Calculate the Total Price of a Shopping Cart?

Problem Statement:
Calculate the total price based on product price and quantity.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const [cart] = useState([
    {
      id: 1,
      name: "Laptop",
      price: 60000,
      quantity: 1
    },
    {
      id: 2,
      name: "Mouse",
      price: 1000,
      quantity: 2
    }
  ]);

  const totalPrice = cart.reduce(
    (total, item) =>
      total + item.price * item.quantity,
    0
  );

  return (
    <div>
      <h1>Shopping Cart</h1>

      {cart.map((item) => (
        <p key={item.id}>
          {item.name} - ₹{item.price} × {item.quantity}
        </p>
      ))}

      <h2>Total: ₹{totalPrice}</h2>
    </div>
  );
}

export default ShoppingCart;

Output:

Shopping Cart

Laptop - ₹60000 × 1
Mouse - ₹1000 × 2

Total: ₹62000

Explanation:
reduce() calculates the total by multiplying each product’s price by its quantity and adding the results.

The total is derived from the cart state, so it does not need to be stored as a separate state value.

Concepts Covered:

  • reduce()
  • Calculations
  • Derived Data
  • Array Methods

7. How to Display the Number of Items in the Shopping Cart?

Problem Statement:
Display the total number of products in the cart based on their quantities.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const [cart] = useState([
    { id: 1, name: "Laptop", quantity: 1 },
    { id: 2, name: "Mouse", quantity: 2 },
    { id: 3, name: "Keyboard", quantity: 1 }
  ]);

  const totalItems = cart.reduce(
    (total, item) => total + item.quantity,
    0
  );

  return (
    <div>
      <h1>Shopping Cart</h1>

      <p>Items in Cart: {totalItems}</p>

      {cart.map((item) => (
        <p key={item.id}>
          {item.name} - {item.quantity}
        </p>
      ))}
    </div>
  );
}

export default ShoppingCart;

Output:

Shopping Cart

Items in Cart: 4

Laptop - 1
Mouse - 2
Keyboard - 1

Explanation:
The number of cart entries is not necessarily the number of products being purchased. For example, one Mouse entry with quantity 2 represents two items. reduce() calculates the total quantity correctly.

Concepts Covered:

  • reduce()
  • Derived Data
  • Array State
  • Quantity Calculation

8. How to Show an Empty Cart Message?

Problem Statement:
Display a useful message when there are no products in the shopping cart.

React Solution:

import { useState } from "react";

function ShoppingCart() {
  const [cart, setCart] = useState([]);

  return (
    <div>
      <h1>Shopping Cart</h1>

      {cart.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        cart.map((item) => (
          <div key={item.id}>
            <p>{item.name}</p>

            <button
              onClick={() =>
                setCart((currentCart) =>
                  currentCart.filter(
                    (product) => product.id !== item.id
                  )
                )
              }
            >
              Remove
            </button>
          </div>
        ))
      )}
    </div>
  );
}

export default ShoppingCart;

Output when cart is empty:

Shopping Cart

Your cart is empty.

Explanation:
The conditional expression checks cart.length. If it is 0, the empty-cart message is shown. Otherwise, the products are rendered.

This improves the user experience because users get meaningful feedback instead of seeing a blank area.

Concepts Covered:

  • Conditional Rendering
  • Ternary Operator
  • Arrays
  • State

9. How to Create Reusable Product and Cart Components?

Problem Statement:
Split the shopping cart into reusable ProductCard and CartItem components.

React Solution:

import { useState } from "react";

function ProductCard({ product, onAdd }) {
  return (
    <div>
      <h3>{product.name}</h3>
      <p>₹{product.price}</p>

      <button onClick={() => onAdd(product)}>
        Add to Cart
      </button>
    </div>
  );
}

function CartItem({
  item,
  onIncrease,
  onDecrease,
  onRemove
}) {
  return (
    <div>
      <h3>{item.name}</h3>

      <p>
        ₹{item.price} × {item.quantity}
      </p>

      <button onClick={() => onDecrease(item.id)}>
        -
      </button>

      <span> {item.quantity} </span>

      <button onClick={() => onIncrease(item.id)}>
        +
      </button>

      <button onClick={() => onRemove(item.id)}>
        Remove
      </button>
    </div>
  );
}

function ShoppingCart() {
  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Mouse", price: 1000 }
  ];

  const [cart, setCart] = useState([]);

  function addToCart(product) {
    setCart((currentCart) => {
      const existingProduct = currentCart.find(
        (item) => item.id === product.id
      );

      if (existingProduct) {
        return currentCart.map((item) =>
          item.id === product.id
            ? { ...item, quantity: item.quantity + 1 }
            : item
        );
      }

      return [
        ...currentCart,
        { ...product, quantity: 1 }
      ];
    });
  }

  function increaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id
          ? { ...item, quantity: item.quantity + 1 }
          : item
      )
    );
  }

  function decreaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id && item.quantity > 1
          ? { ...item, quantity: item.quantity - 1 }
          : item
      )
    );
  }

  function removeFromCart(id) {
    setCart((currentCart) =>
      currentCart.filter((item) => item.id !== id)
    );
  }

  return (
    <div>
      <h1>Shopping Cart</h1>

      <h2>Products</h2>

      {products.map((product) => (
        <ProductCard
          key={product.id}
          product={product}
          onAdd={addToCart}
        />
      ))}

      <h2>Cart</h2>

      {cart.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        cart.map((item) => (
          <CartItem
            key={item.id}
            item={item}
            onIncrease={increaseQuantity}
            onDecrease={decreaseQuantity}
            onRemove={removeFromCart}
          />
        ))
      )}
    </div>
  );
}

export default ShoppingCart;

Output:

Shopping Cart

Products

Laptop
₹60000
[Add to Cart]

Mouse
₹1000
[Add to Cart]

Cart

Your cart is empty.

After adding a Laptop:

Cart

Laptop
₹60000 × 1

[-] 1 [+] [Remove]

Explanation:
The application is divided into reusable components.

  • ProductCard displays a product.
  • CartItem displays an item already in the cart.
  • ShoppingCart owns the cart state and passes data and callback functions through props.

This structure becomes easier to maintain as the application grows.

Concepts Covered:

  • Component Composition
  • Props
  • Callback Functions
  • Reusable Components
  • State Management

10. How to Build a Complete React Shopping Cart?

Problem Statement:
Build a practical Shopping Cart application with:

  • Product listing
  • Add to Cart
  • Duplicate product handling
  • Increase/decrease quantity
  • Remove product
  • Total item count
  • Total price
  • Empty cart message

React Solution:

import { useState } from "react";

function ProductCard({ product, onAdd }) {
  return (
    <div>
      <h3>{product.name}</h3>
      <p>₹{product.price}</p>

      <button onClick={() => onAdd(product)}>
        Add to Cart
      </button>
    </div>
  );
}

function CartItem({
  item,
  onIncrease,
  onDecrease,
  onRemove
}) {
  return (
    <div>
      <h3>{item.name}</h3>

      <p>Price: ₹{item.price}</p>

      <button onClick={() => onDecrease(item.id)}>
        -
      </button>

      <span> {item.quantity} </span>

      <button onClick={() => onIncrease(item.id)}>
        +
      </button>

      <button onClick={() => onRemove(item.id)}>
        Remove
      </button>

      <p>
        Subtotal: ₹{item.price * item.quantity}
      </p>
    </div>
  );
}

function ShoppingCart() {
  const products = [
    {
      id: 1,
      name: "Laptop",
      price: 60000
    },
    {
      id: 2,
      name: "Headphones",
      price: 3000
    },
    {
      id: 3,
      name: "Keyboard",
      price: 1500
    }
  ];

  const [cart, setCart] = useState([]);

  function addToCart(product) {
    setCart((currentCart) => {
      const existingProduct = currentCart.find(
        (item) => item.id === product.id
      );

      if (existingProduct) {
        return currentCart.map((item) =>
          item.id === product.id
            ? {
                ...item,
                quantity: item.quantity + 1
              }
            : item
        );
      }

      return [
        ...currentCart,
        {
          ...product,
          quantity: 1
        }
      ];
    });
  }

  function increaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id
          ? {
              ...item,
              quantity: item.quantity + 1
            }
          : item
      )
    );
  }

  function decreaseQuantity(id) {
    setCart((currentCart) =>
      currentCart.map((item) =>
        item.id === id && item.quantity > 1
          ? {
              ...item,
              quantity: item.quantity - 1
            }
          : item
      )
    );
  }

  function removeFromCart(id) {
    setCart((currentCart) =>
      currentCart.filter((item) => item.id !== id)
    );
  }

  const totalItems = cart.reduce(
    (total, item) => total + item.quantity,
    0
  );

  const totalPrice = cart.reduce(
    (total, item) =>
      total + item.price * item.quantity,
    0
  );

  return (
    <div>
      <h1>React Shopping Cart</h1>

      <h2>Products</h2>

      {products.map((product) => (
        <ProductCard
          key={product.id}
          product={product}
          onAdd={addToCart}
        />
      ))}

      <hr />

      <h2>Shopping Cart</h2>

      <p>Total Items: {totalItems}</p>

      {cart.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        <>
          {cart.map((item) => (
            <CartItem
              key={item.id}
              item={item}
              onIncrease={increaseQuantity}
              onDecrease={decreaseQuantity}
              onRemove={removeFromCart}
            />
          ))}

          <h2>Total Price: ₹{totalPrice}</h2>

          <button>
            Proceed to Checkout
          </button>
        </>
      )}
    </div>
  );
}

export default ShoppingCart;

Output:

React Shopping Cart

Products

Laptop
₹60000
[Add to Cart]

Headphones
₹3000
[Add to Cart]

Keyboard
₹1500
[Add to Cart]

----------------------------

Shopping Cart

Total Items: 0

Your cart is empty.

After adding a Laptop and two Headphones:

Shopping Cart

Total Items: 3

Laptop
Price: ₹60000
[-] 1 [+] [Remove]
Subtotal: ₹60000

Headphones
Price: ₹3000
[-] 2 [+] [Remove]
Subtotal: ₹6000

Total Price: ₹66000

[Proceed to Checkout]

Explanation:
This complete project combines the major concepts required for a basic shopping cart.

The product list is rendered using map(). The cart is stored in state. When a product is added, the application checks whether it already exists. Existing products have their quantity increased, while new products are added with quantity 1.

map() is used for quantity updates, filter() is used for removal, and reduce() calculates the total number of items and total price.

The cart state is owned by the parent ShoppingCart component, while ProductCard and CartItem remain reusable presentation components.

A production e-commerce application can extend this project with product APIs, React Router, authentication, persistent cart storage, server-side cart management, coupon handling, stock validation, checkout, and payment integration.

Concepts Covered:

  • useState
  • Props
  • Callback Functions
  • map()
  • filter()
  • find()
  • reduce()
  • Conditional Rendering
  • Controlled State Updates
  • Immutable Updates
  • Component Composition
  • Shopping Cart Logic

Key Takeaways

  • A Shopping Cart is an excellent React project for practicing real-world state management.
  • useState can store the current cart items.
  • Each cart item can contain product information and a quantity value.
  • find() can check whether a product already exists in the cart.
  • map() can update product quantities without directly mutating the state.
  • filter() can remove products from the cart.
  • reduce() is useful for calculating total items and total prices.
  • Cart totals can be derived from the existing cart state instead of stored as duplicate state.
  • Reusable components such as ProductCard and CartItem make the application easier to maintain.
  • A production shopping cart normally requires backend support for reliable inventory, user accounts, orders, and checkout.

FAQs

1. What is a Shopping Cart in React?

A Shopping Cart in React is an interactive component or application that allows users to add products, change quantities, remove products, and calculate cart totals.

2. Which React Hook is commonly used for a Shopping Cart?

useState is commonly used to manage products and cart items. Other Hooks can be added when features such as API synchronization or Local Storage are required.

3. How do I add a product to a React Shopping Cart?

You can store cart items in state and use setCart() to create a new array containing the selected product. If the product already exists, its quantity can be increased instead.

4. How do I calculate the total price in a React Shopping Cart?

The reduce() method can calculate the total by multiplying each item’s price by its quantity and adding the results.

5. How do I remove an item from a React Shopping Cart?

You can use filter() to create a new cart array that excludes the item with the selected product ID.

6. How do I increase and decrease product quantity in React?

Use map() to find the selected cart item and create a new object with an updated quantity value.

7. Can I build a complete e-commerce Shopping Cart using React?

Yes. React can handle the interactive frontend, including product lists, cart state, quantities, filters, and checkout UI. A real e-commerce system also needs backend services for products, inventory, orders, authentication, and secure payment processing.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top