[React x Context API] Implementation guide for making a shopping cart | Explanation with code

programming

"I want to make a shopping cart using React, but managing the data is difficult."
"I don't know how to use the Context API."
I'm sure there are many people who are worried about this.

In this article, we will introduce ReactHow the Context API makes it easy for anyone to create a shopping cartWe will explain it in detail.

Choose words that even elementary school students can understand.All actual code and configurations included.
We also provide the finished code that can be run by copying and pasting.We are doing it.

Basic functions such as "adding items to the cart", "deleting items", and "calculating the total amount" are available.Easy to understand, sequential contentis.


Why build a shopping cart with React?

How does online shopping and React work together?

Conclusion: Shopping carts are the gateway to web development and a frequently used feature in practice.

Recently, many web services such as online stores and flea market apps have become"Shopping cart function"I have.

for example:

  • Large online shopping sites such as Amazon and Rakuten
  • Handmade sales site for individuals
  • Restaurant online ordering system

What these examples have in common is thatSelect the product, add it to your cart, check the total amount, and purchase it.This is the flow.

React can separate functions into parts,Very suitable for managing the status of the cartWe can say that.

In addition, with the Context API,Access your cart from any screenThis makes it easier to maintain consistency across the entire app.


Introducing and using the Context API

A quick explanation of what the Context API is

Conclusion: A tool for using common data across multiple screens.

In React, we typically pass data from parent to child (props).

However, when the hierarchy is deep, it becomes tedious to pass props every time.

This is where the Context API comes in.

Here's how to use the Context API:

  1. ContextMake
  2. ProviderSurround the whole with
  3. useContextUse data in

This time, we will manage the contents of the cart (product list and total price) using Context.

Steps to set up the Context API

first,CartContext.jsCreate a file and write the following:

1
import { createContext, useState, useContext } from 'react'; const CartContext = createContext(); export const CartProvider = ({ children }) => { const [cartItems, setCartItems] = useState([]); const addToCart = (item) => { setCartItems([...cartItems, item]); }; const removeFromCart = (index) => { const newCart = [...cartItems]; newCart.splice(index, 1); setCartItems(newCart); }; return ( {children} ); }; export const useCart = () => useContext(CartContext);

next,App.jsSo, thisCartProviderSurround it with .

1
import { CartProvider } from './CartContext'; function App() { return ( );

Implementing product list and add to cart function

Let's create a product list page

Bottom line: Display a list of products with a button to add them to the cart.

Below is a simple product list as an example.

1
2
3
4
5
6
7
8
9
10
11
12
import { useCart } from './CartContext'; const products = [ { name: 'Apples', price: 120 }, { name: 'Bananas', price: 80 }, { name: 'Tangerines', price: 100 } ]; function ProductList() { const { addToCart } = useCart(); return (
    <div>
      <h2>Product List</h2>
      {products.map((product, index) =&gt; (
        <div key="{index}">
          {product.name} - ¥{product.price}
          <button onclick="{()" > addToCart(product)}&gt;Add to Cart</button>
        </div>
      ))}
    </div>
  );
}

When you press the "Add to Cart" button on this screen, the cart information will be updated through Context.


Implementing the cart screen and deletion function

View and delete cart contents

Conclusion: Just extract the cart contents from the Context and display them.

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useCart } from &#039;./CartContext&#039;; function Cart() { const { cartItems, removeFromCart } = useCart(); const total = cartItems.reduce((sum, item) =&gt; sum + item.price, 0); return (
    <div>
      <h2>Cart contents</h2>
      {cartItems.map((item, index) =&gt; (
        <div key="{index}">
          {item.name} - ¥{item.price}
          <button onclick="{()" > removeFromCart(index)}&gt; Delete</button>
        </div>
      ))}
      <h3>Total: ¥{total}</h3>
    </div>
  );
}

Summary of shopping cart functions and points to note

Important points for practical use

It is well-structured for learning purposes, butWhen using it in practice, the following points should be noted::

  • Product data is retrieved from the server
  • Cart contents are saved in the browser (localStorage)
  • Quantity management (add multiple of the same product)
  • Display monetary amounts with digit separators

Completed code listing

App.js

1
import ProductList from './ProductList'; import Cart from './Cart'; import { CartProvider } from './CartContext'; function App() { return ( ); } export default App;

ProductList.js

1
2
3
4
5
6
7
8
9
10
11
12
import { useCart } from &#039;./CartContext&#039;; const products = [ { name: &#039;Apples&#039;, price: 120 }, { name: &#039;Bananas&#039;, price: 80 }, { name: &#039;Tangerines&#039;, price: 100 } ]; function ProductList() { const { addToCart } = useCart(); return (
    <div>
      <h2>Product List</h2>
      {products.map((product, index) =&gt; (
        <div key="{index}">
          {product.name} - ¥{product.price}
          <button onclick="{()" > addToCart(product)}&gt;Add to Cart</button>
        </div>
      ))}
    </div>
  );
}

Cart.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useCart } from &#039;./CartContext&#039;; function Cart() { const { cartItems, removeFromCart } = useCart(); const total = cartItems.reduce((sum, item) =&gt; sum + item.price, 0); return (
    <div>
      <h2>Cart contents</h2>
      {cartItems.map((item, index) =&gt; (
        <div key="{index}">
          {item.name} - ¥{item.price}
          <button onclick="{()" > removeFromCart(index)}&gt; Delete</button>
        </div>
      ))}
      <h3>Total: ¥{total}</h3>
    </div>
  );
}

CartContext.js

1
import { createContext, useState, useContext } from 'react'; const CartContext = createContext(); export const CartProvider = ({ children }) => { const [cartItems, setCartItems] = useState([]); const addToCart = (item) => { setCartItems([...cartItems, item]); }; const removeFromCart = (index) => { const newCart = [...cartItems]; newCart.splice(index, 1); setCartItems(newCart); }; return ( {children} ); }; export const useCart = () => useContext(CartContext);

summary

In this article, we will use React and the Context API.A shopping cart app that anyone can easily createWe introduced how to make it.

  • Context lets you access your cart from anywhere
  • Adding or deleting products can be implemented with just a few lines of code.
  • The total amount can be calculated on the spot.

Learn how to create a shopping cart using React, step by stepIt has become.

You may have realized that the cart function, which you may have thought was difficult, is actually quite simple.

Related links:

Copied title and URL