DEV Community

Cover image for How To Set Up Add to Cart Functionality in React
Udemezue John
Udemezue John

Posted on

How To Set Up Add to Cart Functionality in React

Introduction.

Building an e-commerce site with React? One of the most essential features you’ll need is a functional “Add to Cart” button.

It’s more than just an interactive UI element; it’s a key part of the user experience and the sales process.

Without this, your users can’t add products to their cart, adjust quantities, or proceed to checkout.

In this article, I’ll walk you through step-by-step how to implement an “Add to Cart” functionality in React.

How Do I Set Up Add to Cart Functionality in React?

Step 1: Create a Basic Product Listing.

First, you'll need a list of products. Whether you fetch it from an API or create dummy data for testing, the products will typically include details like name, price, and id.

Here’s an example of how a basic product list might look in React:

const products = [
  { id: 1, name: "Laptop", price: 1000 },
  { id: 2, name: "Smartphone", price: 500 },
  { id: 3, name: "Headphones", price: 150 },
];
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting up State for Cart Items.

In React, I use the useState hook to manage the cart’s state. Initially, the cart will be empty, so I start with an empty array.

import { useState } from "react";

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

Enter fullscreen mode Exit fullscreen mode

Step 3: Handling the Add to Cart Button.

Next, I’ll need a function to handle adding products to the cart. This function will take a product as an argument and add it to the existing cart state. If the product is already in the cart, it will just increase the quantity.

const addToCart = (product) => {
  const productInCart = cart.find((item) => item.id === product.id);
  if (productInCart) {
    setCart(
      cart.map((item) =>
        item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
      )
    );
  } else {
    setCart([...cart, { ...product, quantity: 1 }]);
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Rendering the Products and Add to Cart Button.

Now, I’ll create a simple UI that displays the product list, each with an “Add to Cart” button. When the button is clicked, the addToCart function will be triggered.

return (
  <div>
    {products.map((product) => (
      <div key={product.id}>
        <h2>{product.name}</h2>
        <p>Price: ${product.price}</p>
        <button onClick={() => addToCart(product)}>Add to Cart</button>
      </div>
    ))}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Step 5: Displaying the Cart.

To see which items the user has added to the cart, I need to render the cart state. Below is a basic example that lists the products and their quantities.

return (
  <div>
    <h1>Shopping Cart</h1>
    {cart.map((item) => (
      <div key={item.id}>
        <h2>{item.name}</h2>
        <p>Quantity: {item.quantity}</p>
      </div>
    ))}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Step 6: Updating Quantities and Removing Items.

Adding functionality to update or remove items from the cart makes the system more dynamic.

Here’s an example of a function that allows users to adjust quantities or remove items.

const updateQuantity = (productId, quantity) => {
  if (quantity === 0) {
    setCart(cart.filter((item) => item.id !== productId));
  } else {
    setCart(
      cart.map((item) =>
        item.id === productId ? { ...item, quantity: quantity } : item
      )
    );
  }
};

Enter fullscreen mode Exit fullscreen mode

Now, by updating the UI with input fields for quantity, I can give users full control over their shopping cart:

return (
  <div>
    <h1>Shopping Cart</h1>
    {cart.map((item) => (
      <div key={item.id}>
        <h2>{item.name}</h2>
        <input
          type="number"
          value={item.quantity}
          onChange={(e) => updateQuantity(item.id, parseInt(e.target.value))}
        />
      </div>
    ))}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Conclusion.

Adding “Add to Cart” functionality in React is an essential part of any e-commerce project.

It’s relatively straightforward but can grow in complexity based on your project's needs.

By managing the state with hooks and handling product quantities dynamically, you can build a flexible and efficient shopping cart system.

So, after understanding how this works, do you think it’s worth building your own cart from scratch, or would you rather go for a third-party library?

Top comments (0)