Back To Tutorials

React Shopping Cart

Intermediatechallenge

This tutorial will walk you through building a simple shopping cart using React. The cart will allow users to add, remove, and update the quantity of products. We'll also calculate the total price and display it dynamically.

Objective

By the end of this tutorial, you will have created a functional shopping cart in React that utilizes state management to handle product additions, quantity updates, and total price calculation.

Requirements

  • Basic understanding of React and JavaScript ES6+
  • Node.js and npm installed on your machine
  • A text editor (e.g., VS Code, Sublime Text)
  • Basic knowledge of CSS for simple styling

Resources

Steps

Step 1: Create a New React App

First, create a new React project using Create React App.

npx create-react-app react-shopping-cart
cd react-shopping-cart
npm start

Step 2: Create the Product Data

Inside your src folder, create a file called data.js to hold an array of product objects.

// src/data.js
export const products = [
  {
    id: 1,
    name: 'Product 1',
    price: 29.99,
    image: 'https://via.placeholder.com/150',
  },
  {
    id: 2,
    name: 'Product 2',
    price: 39.99,
    image: 'https://via.placeholder.com/150',
  },
  {
    id: 3,
    name: 'Product 3',
    price: 49.99,
    image: 'https://via.placeholder.com/150',
  },
];

Step 3: Create the Product Component

Create a Product component to display individual products.

// src/components/Product.js
import React from 'react';

const Product = ({ product, addToCart }) => {
  return (
    <div className="product">
      <img src={product.image} alt={product.name} />
      <h3>{product.name}</h3>
      <p>${product.price.toFixed(2)}</p>
      <button onClick={() => addToCart(product)}>Add to Cart</button>
    </div>
  );
};

export default Product;

Step 4: Create the Cart Component

Create a Cart component to display items added to the cart and allow quantity adjustments.

// src/components/Cart.js
import React from 'react';

const Cart = ({ cartItems, removeFromCart, updateQuantity }) => {
  const totalPrice = cartItems.reduce((total, item) => total + item.price * item.quantity, 0);

  return (
    <div className="cart">
      <h2>Your Cart</h2>
      {cartItems.length === 0 ? (
        <p>Cart is empty</p>
      ) : (
        <ul>
          {cartItems.map(item => (
            <li key={item.id}>
              <img src={item.image} alt={item.name} />
              <div>
                <h3>{item.name}</h3>
                <p>Price: ${item.price.toFixed(2)}</p>
                <p>
                  Quantity: 
                  <input
                    type="number"
                    value={item.quantity}
                    min="1"
                    onChange={(e) => updateQuantity(item.id, Number(e.target.value))}
                  />
                </p>
                <button onClick={() => removeFromCart(item.id)}>Remove</button>
              </div>
            </li>
          ))}
        </ul>
      )}
      <h3>Total: ${totalPrice.toFixed(2)}</h3>
    </div>
  );
};

export default Cart;

Step 5: Create the Main App Component

In App.js, import the product data and components, and handle state management for the cart.

// src/App.js
import React, { useState } from 'react';
import { products } from './data';
import Product from './components/Product';
import Cart from './components/Cart';

const App = () => {
  const [cartItems, setCartItems] = useState([]);

  const addToCart = (product) => {
    const existingItem = cartItems.find(item => item.id === product.id);

    if (existingItem) {
      setCartItems(cartItems.map(item => 
        item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
      ));
    } else {
      setCartItems([...cartItems, { ...product, quantity: 1 }]);
    }
  };

  const removeFromCart = (id) => {
    setCartItems(cartItems.filter(item => item.id !== id));
  };

  const updateQuantity = (id, quantity) => {
    setCartItems(
      cartItems.map(item => (item.id === id ? { ...item, quantity } : item))
    );
  };

  return (
    <div className="App">
      <h1>React Shopping Cart</h1>
      <div className="products">
        {products.map(product => (
          <Product key={product.id} product={product} addToCart={addToCart} />
        ))}
      </div>
      <Cart cartItems={cartItems} removeFromCart={removeFromCart} updateQuantity={updateQuantity} />
    </div>
  );
};

export default App;

Step 6: Style the Application

Create a styles.css file to add basic styles for the product listing and cart.

*{
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    padding: 20px;
  }
  
  h1 {
    text-align: center;
  }
  
  .products {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
  }
  
  .product {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
    width: 200px;
    border-radius: 5px;
  }
  
  .product img {
    width: 150px;
    height: 100px;
  }
  
  .cart {
    border-top: 1px solid #ccc;
    padding-top: 20px;
  }
  
  .cart ul {
    list-style-type: none;
    padding: 0;
  }
  
  .cart li {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    
    max-width: 30%;
    display: inline-flex;
    margin-left: 3%;
    border: 1px solid gray;
    border-radius: 5px;
  }
  
  .cart li img {
    width: 80px;
    height: 50px;
  }
  
  button {
    cursor: pointer;
  }
  
  *{
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    padding: 20px;
  }
  
  h1 {
    text-align: center;
  }
  
  .products {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
  }
  
  .product {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
    width: 200px;
    border-radius: 5px;
  }
  
  .product img {
    width: 150px;
    height: 100px;
  }
  
  .cart {
    border-top: 1px solid #ccc;
    padding-top: 20px;
  }
  
  .cart ul {
    list-style-type: none;
    padding: 0;
  }
  
  .cart li {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    
    max-width: 30%;
    display: inline-flex;
    margin-left: 3%;
    border: 1px solid gray;
    border-radius: 5px;
  }
  
  .cart li img {
    width: 80px;
    height: 50px;
  }
  
  button {
    cursor: pointer;
  }

Make sure to import the styles in App.js:

// src/App.js
import './styles.css';

Step 7: Run Your Project

Open the terminal and run npm start.
Open the app in your browser, and you should now be able to add, remove, and update items in the cart, with a dynamic total price.