DEV Community

ABHISHEK M
ABHISHEK M

Posted on

How I Built a Shopping Cart in React: A Step-by-Step Guide

Hello DEV community!

For the past few months, I've been working on a personal project called "BuzzOrders," a full-stack food ordering application for movie theaters. The goal was to build a complete, real-world application from scratch using React for the frontend and Python for the backend.

One of the most critical features of any ordering app is the shopping cart. It needs to be fast, reliable, and user-friendly. In this article, I’ll walk you through the simple yet effective approach I took to build the shopping cart functionality using modern React Hooks.

Step 1: Setting Up the Cart State
First things first, we need a place to store the items that the user adds to their cart. Since we're using functional components in React, the useState hook is the perfect tool for this. I initialized our cart state as an empty array.

JavaScript

import React, { useState } from 'react';

function App() {
// cartItems will hold an array of products in the cart
const [cartItems, setCartItems] = useState([]);

// ... rest of the component
}
This simple line gives us a state variable cartItems and a function setCartItems to update it.

Step 2: The "Add to Cart" Functionality
This is where the core logic lives. When a user clicks an "Add to Cart" button on a product, we need to do two things:

Check if the item is already in the cart.

If it is, just increase its quantity. If it's not, add the new item to the cart with a quantity of 1.

Here is the function I wrote to handle this logic:

JavaScript

const addToCart = (product) => {
// Check if the product already exists in the cart
const exist = cartItems.find((item) => item.id === product.id);

if (exist) {
// If it exists, map through the cart and increase the quantity of that product
setCartItems(
cartItems.map((item) =>
item.id === product.id ? { ...exist, quantity: exist.quantity + 1 } : item
)
);
} else {
// If it doesn't exist, add the new product to the cart with a quantity of 1
setCartItems([...cartItems, { ...product, quantity: 1 }]);
}
};
This function is powerful because it handles both adding new items and updating existing ones, preventing duplicate entries in our cart.

Step 3: Displaying the Cart Items
Now that we can add items to our cartItems state, we need to show them to the user. This is straightforward in React. We can simply .map() over the cartItems array and render a piece of JSX for each item.

Here’s a basic example of how the cart component might look:

JavaScript

<div className="cart">
  <h2>Your Cart</h2>
  {cartItems.length === 0 ? (
    <div>Cart is empty</div>
  ) : (
    <ul>
      {cartItems.map((item) => (
        <li key={item.id}>
          {item.name} - ${item.price} x {item.quantity}
        </li>
      ))}
    </ul>
  )}
</div>
Enter fullscreen mode Exit fullscreen mode

This code first checks if the cart is empty. If it's not, it lists out each item along with its name, price, and the current quantity in the cart.

Conclusion
Building a shopping cart in React doesn't have to be overly complex. By using the useState hook and some simple JavaScript logic, you can create a robust and functional cart for any small to medium-sized e-commerce application.

This is just the foundation, of course. For a more advanced application, I would explore using the Context API or Redux to manage state across different components without having to pass props down manually.

Thanks for reading! I hope this was helpful. This was a really fun feature to build, and I learned a lot in the process. You can check out the full source code for my "BuzzOrders" project on my GitHub.

Feel free to leave any questions or suggestions in the comments below!

GitHub Link: https://github.com/abhi91543/BuzzOrders


Enter fullscreen mode Exit fullscreen mode

Top comments (0)