Implementing Cart Functionality in React with Context API
1081 6 mins
Implementing a shopping cart functionality using React’s Context API allows you to manage the cart items across your application seamlessly. Below, I’ll guide you step-by-step on how to set up a cart context, add items to the cart, and display the cart count in the header.
Step 1: Create the Cart Context
First, you need to create a context that will manage the cart items and provide functions to manipulate the cart contents.
Setting Up CartContext
Create the Context: Define a new context that will hold the cart items.
CartProvider Component: This component will provide the cart state and functions to modify it to other components.
useCart Custom Hook: This hook simplifies accessing the cart context from any component.
Here’s how you can set up and use the CartContext:
Step 2: Modify the App Component to Include CartProvider
You’ll need to wrap your application’s component tree with the CartProvider to make sure the cart context is accessible throughout your application. This involves a slight restructuring of your existing setup to nest the CartProvider within the UserContext.Provider.
Here’s how to integrate the CartProvider into your existing App component:
// src/App.js
importReactfrom"react";import{BrowserRouter,Routes,Route}from"react-router-dom";importHeaderfrom"./Components/Header";importDashboardfrom"./Pages/Dashboard/Dashboard";importHomefrom"./Pages/Home/Home";importLoginfrom"./Pages/Login/Login";importNotFoundfrom"./Pages/NotFound/NotFound";importProfilefrom"./Pages/Profile/Profile";importSignUpfrom"./Pages/SignUp/SignUp";importUserContextfrom"./UserContext";import{CartProvider}from"./CartContext";// Make sure to import CartProvider
constApp=()=>{return(<><UserContext.Providervalue={"babu"}><CartProvider>{" "}{/* CartProvider wrapped inside UserContext.Provider */}<BrowserRouter><div><Header/><Routes><Routepath="/"element={<Login/>}/><Routepath="/home"element={<Home/>}/><Routepath="/dashboard"element={<Dashboard/>}/><Routepath="/login"element={<Login/>}/><Routepath="/profile"element={<Profile/>}/><Routepath="/signup"element={<SignUp/>}/><Routepath="*"element={<NotFound/>}/></Routes></div></BrowserRouter></CartProvider></UserContext.Provider></>);};exportdefaultApp;
Step 3: Add Items to the Cart
Implementing shopping cart functionality in React applications is streamlined by using the Context API, which allows for seamless management of cart items across all components. This guide will walk you through setting up a cart context, adding items to the cart, and displaying the cart count in the header.
1. Set Up a Sample Product Array
First, you’ll need an array of products that your application can display. Each product in the array should have properties like id, name, description, price, and image URL.
constproducts=[{id:1,name:"Product 1",description:"Description of product 1",price:9.99,image:"https://example.com/product1.jpg",},{id:2,name:"Product 2",description:"Description of product 2",price:19.99,image:"https://example.com/product2.jpg",},{id:3,name:"Product 3",description:"Description of product 3",price:29.99,image:"https://example.com/product3.jpg",},];
2. Create a ProductCard Component
This component will display an individual product. It should include an image, description, price, and an “Add to Cart” button.
// src/components/ProductCard.js
importReactfrom"react";import{useCart}from"../CartContext";// Make sure to import useCart from your CartContext
functionProductCard({product}){const{addToCart}=useCart();consthandleAddToCart=()=>{addToCart(product);};return(<divclassName="card"style={{width:"18rem"}}><imgsrc={product.imageUrl}className="card-img-top"alt={product.name}/><divclassName="card-body"><h5className="card-title">{product.name}</h5><pclassName="card-text">{product.description}</p><pclassName="card-text">${product.price}</p><buttonclassName="btn btn-primary"onClick={handleAddToCart}>AddtoCart</button></div></div>);}exportdefaultProductCard;
3. Display Products on a Product Page
Create a ProductsPage component that uses the ProductCard to display each product.
By following these steps, you have successfully integrated a cart functionality into your React application using the Context API. This allows for seamless state management of cart items, ensuring a smooth user experience across different components of your application.